Web API Routing - Only actions with a URI parameter work

旧城冷巷雨未停 提交于 2019-12-13 00:09:31

问题


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.

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 }
        );
    }        
}

Here is the controller class:

[Authorize]
[RoutePrefix("api/WikiPlan")]
public class WikiPlanController : ApiController

Here's the action that works:

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!


回答1:


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.

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.



来源:https://stackoverflow.com/questions/24591888/web-api-routing-only-actions-with-a-uri-parameter-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!