Web API路由-仅具有URI参数的操作有效 [英] Web API Routing - Only actions with a URI parameter work
问题描述
我有一个运行良好的Web API项目.我将其与MVC项目合并,现在只有带有URI参数的操作有效.所有其他操作最终都以404 Not Found结束,甚至找不到控制器.
I had a web API project that was working fine. I merged it with an MVC project, and now only the actions with a URI parameter work. All other actions end up with a 404 Not Found where even the controller is not found.
这就是我在WebApiConfig中拥有的东西(标准的东西):
Here's what I have in WebApiConfig (standard stuff):
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
这是控制器类:
[Authorize]
[RoutePrefix("api/WikiPlan")]
public class WikiPlanController : ApiController
这是可行的操作:
http://localhost:2000/api/WikiPlan/SearchWikiPlans/baby
[AllowAnonymous]
[HttpGet]
[Route("SearchWikiPlans/{keyword}")]
[ResponseType(typeof(List<WikiPlanSearchResultViewModel>))]
public IHttpActionResult SearchWikiPlans(string keyword)
这是一个不起作用的代码(曾经在其自己的项目中起作用):
Here's one that doesn't work (which used to work when it was in its own project):
http://localhost:2000/api/WikiPlan/TopWikiPlans
[AllowAnonymous]
[HttpGet]
[Route("TopWikiPlans")]
[ResponseType(typeof(List<TopWikiPlan>))]
public IHttpActionResult TopWikiPlans()
我不知道怎么了.感谢您的帮助!
I don't know what is wrong. Thanks for your help!
推荐答案
Thanks to this Route Debugger tool (http://blogs.msdn.com/b/webdev/archive/2013/04/04/debugging-asp-net-web-api-with-route-debugger.aspx), I was able to trace the broken URL and figured out the issue.
原来,框架是根据MVC路由而不是我的API路由来匹配损坏的URL.因此,我将调用转移到在Global.asax的MVC路由顶部注册API路由,现在它已正确匹配.
Turned out the Framework was matching the broken URL against the MVC route rather than my API routes. So I moved the call to register the API routes on top of the MVC route in Global.asax, and it is now matched correctly.
这篇关于Web API路由-仅具有URI参数的操作有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!