一张图说明 Web Api 参数绑定默认规则

 

请求如下:

 

 

控制器如下:

 

 

慎重说明:不管请求方式是 get 还是 post , 简单类型的参数,如 name 和 id ,其值都是从 url 里面去取.

Web API 从 url 还是 body 获取 简单类型参数的值,跟客户端提交的方式没有任何关系,只跟 [FromBody] 和 [FromUri] 有关系

这里还有两个需要注意的地方:

1.get 请求

如果是通过 Get 方式获取基础类型参数,比如:

那么,传入的参数个数不能比接收的少,比如:

正确写法:

http://localhost:57895/api/test/TestParam?name=www&id=1

或者

http://localhost:57895/api/test/TestParam?name=www&id=1&age=100

但是,下面这种写法请求不到api

http://localhost:57895/api/test/TestParam?name=www

2.post请求

如果想通过 Post 方式获取基础类型参数,比如:

通常,大家都会这样写:

            $.ajax({
                type: "post",
                url: "http://localhost:42561/api/order/pager",
                data: "{ name: 'wjire' }",
                contentType: "application/json",
                success: function () {
                }
            });

又或者这样写:

            $.ajax({
                type: "post",
                url: "http://localhost:42561/api/order/pager",
                data: { name: "wjire" },
                contentType: "application/x-www-form-urlencoded",
                success: function () {
                }
            });

但,都是错的!!

正确写法是这样的:

            $.ajax({
                type: "post",
                url: "http://localhost:42561/api/order/pager",
                data: { "": "hello" },
                contentType: "application/x-www-form-urlencoded",
                success: function () {
                }
            });

相当恶心的写法,但确实是对的,

但是问题又来了,Web Api 是不支持入参有多个 FromBody 的,也就是说,Web Api只允许一个参数读取请求主体中的数据。

[HttpPost]
        public bool Pager([FromBody]string NAME, [FromBody] string DES)
        {
            return true;
        }
            $.ajax({
                type: "post",
                url: "http://localhost:42561/api/order/pager",
                data: { "": "hello","":123 },
                contentType: "application/x-www-form-urlencoded",
                success: function () {
                }
            });

这种写法,是错误的!

因此,如果是从body中取基本类型参数,我们一般都会封装成实体,如开篇截图的例子.

问题又来了,因为如果我们前后台每次传递多个参数的post请求都去新建一个类的话,我们系统到时候会有很多这种参数类?维护起来那是相当的麻烦的一件事,这时候用 dynamic 是一个不错的选择,如:

            $.ajax({
                type: "post",
                url: "http://localhost:42561/api/order/pager",
                data: '{ name: "hello", id: 123 }',
                contentType: "application/json",
                success: function () {
                }
            });

 

 

其次还可以用 Dictionary ,比如:

 

 

不过,貌似没有 dynamic  高级.

实体类参数的传递就简单多了,两种方式:

方式一:

                data: { name: "hello", id: 1233333 },
                contentType: "application/x-www-form-urlencoded",//可以不写,默认就是这个格式

方式二:

                data: "{ name: 'hello', id: 123 }",
                contentType: "application/json",

 

posted @ 2018-01-27 23:42  热敷哥  阅读(417)  评论(0编辑  收藏  举报