我正在解決MVC 3 Web API中的路由問題。它似乎應該很簡單,但我沒有取得任何進展。MVC 3 Web API路由不工作
我的錯誤是:
<Error>
<Message>The request is invalid.</Message>
<MessageDetail>
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'Boolean NewViolationsPublished(Int32)' in 'BPA.API.Controllers.CacheManagementController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
</MessageDetail>
</Error>
我的RegisterRoutes是這樣的:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "NukeAllItemsFromCache",
routeTemplate: "api/CacheManagement/NukeAllItemsFromCache");
routes.MapHttpRoute(
name: "ControllerAndAction",
routeTemplate: "api/{controller}/{action}"
);
routes.MapHttpRoute(
name: "ControllerAndActionAndId",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional, action = "Get" },
constraints: new { id = @"^\d+$" } // Only integers
);
routes.MapHttpRoute(
name: "ControllerAndId",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"^\d+$" } // Only integers
);
}
我的控制器(我拿出代碼爲了便於閱讀):
public class CacheManagementController : ApiController
{
public CacheManagementController()
[HttpGet]
public bool NewViolationsPublished(int id)
[HttpGet]
public bool IsCached(CachedItemLabels label, int clientId)
[HttpGet]
public void RemoveItemFromCache(int clientId, CachedItemLabels cacheLabel, string test)
[HttpGet]
public string NukeAllItemsFromCache()
}
我嘗試撥打電話時出現錯誤:
http://localhost/api/CacheManagement/NukeAllItemsFromCache
TIA
您是否嘗試過你的路線移動到底部,第一加載默認值? – 2013-04-11 19:10:43
我剛剛將NukeAllItemsFromCache路由移動到RegisterRoutes方法的底部,並得到相同的錯誤。 – 2013-04-11 19:14:12
爲什麼你不使用{控制器}/{動作}的默認路線來擊中它? (對不起,只是試圖理解這裏的邏輯)你也使用clientId的RemoveItemFromCache與一些額外的參數,但你的路線狀態它是ID,你是否能夠擊中任何其他路線? – 2013-04-11 19:21:06