ASP.NET WebAPI 路由规则与POST数据

蛋疼的路由规则约定

上一篇文章

我们成功通过AJAX获取到了服务器的数据,

而且服务器根据请求的类型,格式化数据之后再传给客户端。

然而

在上一篇的实例中,

我们为controller程序增加一个GetProducts方法

让这个方法与GetAllProducts方法逻辑一致

        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        public IEnumerable<Product> GetProducts()
        {
            return products;
        }
 

再运行程序,

发现前端AJAX已经无法正常获取数据了

image

对于AJAX请求

服务端返回如下内容

Multiple actions were found that match the request:

System.Collections.Generic.IEnumerable`1[HelloWebAPI.Models.Product] GetAllProducts() on type HelloWebAPI.Controllers.ProductsController\r\nSystem.Collections.Generic.IEnumerable`1[HelloWebAPI.Models.Product] GetProducts() on type HelloWebAPI.Controllers.ProductsController

也就是说

有两个同样的action满足这个请求( $.getJSON("api/products/",………..)

如果你尝试把Action名字加在请求的路径当中

比如$.getJSON("api/products/GetProducts/"….

那么就会得到这样的反馈:

"The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'HelloWebAPI.Models.Product GetProductById(Int32)' in 'HelloWebAPI.Controllers.ProductsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."

也就是说这个请求与

GetProductById(int id)

这个Action冲突了!

查阅微软说明得知:

在Web API的controller当中

只要方法名以“Get”开头

就会匹配所有的Get请求

同理以Post开头的方法

将匹配所有的Post请求

(目前我个人认为这是一个非常蛋疼的约定!!!)

小尾鱼也这么认为)

插播一句

VS2012中注释与取消注释的快捷图标改成这样

image

也是非常蛋疼的改变!还以为是要插入个tip框!

接收POST请求

我们为实例中的controller增加一个方法

        public Product PostProduct(Product item)
        {
            //do what you want
            return item;
        }
 

这个方法接收一个Product实体

这个实体是POST来的数据自动序列化得来的

这个工作是由WEB API完成的

在客户端POST数据的js代码如下:

            function addProduct() {
                var da = { "Id": "1", "Name": '我POST来的数据', "Category": 'Groceries', "Price": "1.39" };
                var ok = function(){alert("ok");}
                $.post("api/Products/", da, ok, "json");
            }
            $(addProduct);
 

前端传递的JSON对象,在ACTION中被序列化为实体类型。

如下图:

DN$E(GR)3W44~9YIQN2LVW3

好吧,假设我们没有一个类型与传递的json对象相对应

该如何是好呢?

我首先想到的是把参数改成string类型的

但string类型的参数并不能接收到任何内容

如下图所示

image

看来我的想法是错误的

我想总会有办法解决这个问题

就此搁笔

希望喜欢的朋友推荐,并留言!

原文地址:https://www.cnblogs.com/liulun/p/2551869.html