简体   繁体   中英

MapHttpAttributeRoutes not working with areas - every route 404s

I'm completely stuck on this - after commenting out almost everything to do with startup configuration leaving only the following, I still can't get the WebApi Attribute routing to work correctly.

I have the following Global.asax.cs:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

The following controller - located in an area called "v2":

[RoutePrefix("v2/businesses")]
public class BusinessesController : ApiController
{
    // GET: v2/businesses/{id}
    [HttpGet]
    [Route("{id:int}")]
    public ApiResponse<ApiBusiness> Index(int id)
    {

        return new ApiResponse<ApiBusiness>(new ApiBusiness());

    }
}

The following area registration:

public class V2AreaRegistration : AreaRegistration 
{
    public override string AreaName 
    {
        get 
        {
            return "v2";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.Routes.MapMvcAttributeRoutes();
    }
}

And the following WebApiConfig:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
    }
}

When I try to access the endpoint URL businesses/1 or v2/businesses/1 or v2/v2/businesses/1 all three return a 404, I was sure one of those would be correct.

Note that a different controller outside of the "v2" area works perfectly fine:

[RoutePrefix("abc")]
public class TestingController : ApiController
{
    [HttpGet]
    [Route("123")]
    public int Test()
    {
        return 2;
    }
}

Sure enough, 2 is returned when I access that endpoint ( abc/123 ).

Can anyone explain why this isn't working?

In this situation you are saying that "v2" is both and mvc route AND a web api route; they can't coexist. I mean, they can, but what happens here is that the requests to the web API will be mistakenly handled as if they were an MVC action. That's why you get a 404.

In less words, Web API doesn't really support areas. What you can do here is try to register the web api routing before the mvc routing or explicitly handle the web api rounting using MapHttpRoute . For example:

context.Routes.MapHttpRoute("AreaName_WebApiRoute",
    "AreaName/Api/{controller}/{id}",
    new { id = RouteParameter.Optional });

Check this SO answer for more details!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM