嘗試在Visual Studio 2010中使用MVC RC4 Web API設置新站點,但它似乎不起作用:參數值永遠不會傳遞給方法。MVC4 Web API忽略參數
至於我可以告訴我所做的一切,正是因爲這裏描述:http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
路由配置:
routes.Clear();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new {
id = RouteParameter.Optional
}
);
下面是常規MVC的路線,我也試着只刪除這完全看是否有 是有些衝突,但它沒有任何區別。
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
測試控制器:
public class TestController : ApiController
{
[HttpGet]
public int Double(int value)
{
return value * 2;
}
}
網址:http://localhost:1505/api/test/double/4
The parameters dictionary contains a null entry for parameter 'value' of
non-nullable type 'System.Int32' for method 'Int32 Double(Int32)' in
'MyAppName.Controllers.TestController'. An optional parameter must be a
reference type, a nullable type, or be declared as an optional parameter.
哎呀。這只是簡單而已,不是嗎?但似乎沒有任何結果參數被映射。對於這個問題我也試過
http://localhost:1505/api/test/double?id=4
沒什麼區別。如果我讓參數接受空值,例如
public int Double(int? value)
它運行,但value
始終爲空。
我在做什麼錯?
所以基本上,方法中的參數名稱必須與模板中使用的名稱相匹配?這是否意味着我必須爲每種可能的方法創建一個路徑,即使它匹配現有的模式(或者使用ID作爲我的參數名稱,無論如何)?呃.. – 2012-07-17 13:40:38
@jamietre這有點過分簡化了,但是。在MVC和Web.API中,稱爲ModelBinder的組件負責將傳入數據(來自集合的路由參數,查詢字符串)與參數對象進行匹配。它與名字相匹配。如果您需要更多信息,您可以搜索ModelBinder和ValueProviders。 – nemesv 2012-07-17 13:42:50
謝謝。會做。似乎不尋常的是它與實際的參數名稱相匹配,而不僅僅是簽名,這種類型打敗了模板的目的! – 2012-07-17 13:43:39