蛋疼的路由規則約定
在上一篇文章中
我們成功通過AJAX獲取到了服務器的數據,
而且服務器根據請求的類型,格式化數據之后再傳給客戶端。
然而
在上一篇的實例中,
我們為controller程序增加一個GetProducts方法
讓這個方法與GetAllProducts方法邏輯一致
再運行程序,
發現前端AJAX已經無法正常獲取數據了
對於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中注釋與取消注釋的快捷圖標改成這樣
也是非常蛋疼的改變!還以為是要插入個tip框!
接收POST請求
我們為實例中的controller增加一個方法
這個方法接收一個Product實體
這個實體是POST來的數據自動序列化得來的
這個工作是由WEB API完成的
在客戶端POST數據的js代碼如下:
前端傳遞的JSON對象,在ACTION中被序列化為實體類型。
如下圖:
好吧,假設我們沒有一個類型與傳遞的json對象相對應
該如何是好呢?
我首先想到的是把參數改成string類型的
但string類型的參數並不能接收到任何內容
如下圖所示
看來我的想法是錯誤的
我想總會有辦法解決這個問題
就此擱筆
希望喜歡的朋友推薦,並留言!