有关WebApi的琐碎记录

1、关于Controller:使用方法名或者控制器名作为接口地址

问题:新建的WebApi的项目生成的接口的地址都是以控制器的名字命名的,这样的话,在方法前添加ActionName就不起作用了。

接口代码:

复制代码
 public class ValuesController : ApiController
    {
        /// <summary>
        /// 接口地址测试
        /// </summary>
        /// <returns></returns>
        [System.Web.Http.ActionName("Rename")]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }
复制代码

生成的接口地址:

折腾了一番,才想起来ASP.NET中有个叫路由的东西。OK,修改App_Start/WebApiConfig.cs

修改前代码:

routeTemplate: "api/{controller}/{id}",

修改后代码:

routeTemplate: "api/{controller}/{action}/{id}",

修改后的接口地址:

 

 

2、WebAPI的属性和相关操作 FormBody和 FormUri等

(1)FromUri

将数据通过url方式传递。需要在webapi方法标明(一般get方法使用),这个参数只接受url中参数的值。

webapi使用:

复制代码
// 一般结合Dto使用
public IEnumerable<Person> GetAllPerson([FromUri] GetAllPersonInput input)
{
    return new List<Person>() {
        new Person() {ID="1", Name="Moby",Age=15},
        new Person() {ID="2", Name="Job",Age=15} };
}

// Dto定义
public class GetBaseInput
{
    public string Id { get; set; }
    public string Name { get; set; }
}

// 不用Dto
public IEnumerable<Person> GetAllPerson([FromUri] string Id, [FromUri] string Name)
{
    return new List<Person>() {
        new Person() {ID="1", Name="Moby",Age=15},
        new Person() {ID="2", Name="Job",Age=15} };
}
复制代码

ajax使用:

复制代码
$.ajax({
    url: 'http://localhost:21162/api/person/?str1=1&str2=3',
    type: 'Get',
    dataType: 'json',
    success: function (data, textStatus, xhr) {
        console.log(data);
    },
    error: function (xhr, textStatus, errorThrown) {
        console.log('Error in Operation');
    }
});
复制代码

 

(2)FromBody

结合Post方法,使用和FromUri相似

复制代码
// 结合Dto使用
[HttpPost]
public IEnumerable<Person> EditPerson([FromBody] PersonDto input)
{
   …………
}

// Dto定义
public class PersonDto
{
    public string Id { get; set; }
    public string Name { get; set; }
    public int Age{ get; set; }
}
复制代码

 

本文作者:暴躁老砚

本文链接:https://www.cnblogs.com/Yan3399/p/16481168.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   暴躁老砚  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2021-07-15 面向对象VS面向过程
2021-07-15 有关DDD、IOC、OOP、AOP
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.