WebAPI 2 Attribute routing with areas not working

主宰稳场 提交于 2019-12-10 16:47:36

问题


I'm having trouble getting WEBAPI 2 attribute routing to work. The routing scheme I'm looking for is /api/{product}/{controller}/{id-optional}, so like /api/Vision/IdCard. The controllers are in an area and are set up like this:

namespace DataServices.Controllers.Vision
{
     [RoutePrefix("api/vision")]
        public class IdCardController : BaseApiController
        {
            [System.Web.Mvc.RequireHttps]
            [Route("idcard")]
            public IdCardViewModel Get(HttpRequestMessage request)
            {...}

Whenever I do a get to this, I get a 404. I included the namespace as the area is in it's own namespace. Are areas supported in WEBAPI attribute routing?

EDIT: WebApiConfig looks like this:

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

回答1:


You need to get the HttpConfiguration instance from the GlobalConfiguration object and call the MapHttpAttributeRoutes() method from inside the RegisterArea method of the AreaRegistration.cs.

    public override void RegisterArea(AreaRegistrationContext context) 
    {
        GlobalConfiguration.Configuration.MapHttpAttributeRoutes();

        //... omitted code  
    }

This must be done for each Area. Finally you must in the 'WebApiConfig' remove "config.MapHttpAttributes()" method or you will get duplicate exception.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.EnableCors();

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



回答2:


Is the project a MVC project from start? Then I think you should remove the "ApiAreaRegistration.cs" file created when you created the area. It's found in the root of the your Api area and it will conflict with your attribute routes as it will match on a MVC (not WebApi) route like "api/{controller}/{action}/{id}" before it finds your specific routes.

Hope it helps!




回答3:


Area functionality not available in Asp.Net Web API project, and its harder to maintain with custom way like Namespace based controller. I have checked many problems with namespace based controller and routing, like single action method is accessible by namespace based routing as well as default routing.Thus custom implementation does not mitigate our requirements.

To resolve this issue we can use simple way to manage controllers routing as :

      //Remove default routing registration      
      /*config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );*/

And use just attribute based routing only, like

[RoutePrefix("api/user/home")]
public class UserHomeController : ApiController
{
     [Route]
     public string Get()
     {
       return "Test user GET";
     }
}

And for different area/module controller

[RoutePrefix("api/admin/home")]
public class AdminHomeController : ApiController
{
     [Route]
     public string Get()
     {
       return "Test admin GET";
     }
}

Advantages with this approach are:

  • No need of custom logic like namespace based area, custom routing handler, so its better way to code.
  • Just need to add attribute [Route] in action to availability in API



回答4:


Try play with initialization order in Application_Start Thus:

//Config WebAPI(2) where you call config.MapHttpAttributeRoutes();
  • GlobalConfiguration.Configure(WebApiConfig.Register);

  • AreaRegistration.RegisterAllAreas();

  • FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  • RouteConfig.RegisterRoutes(RouteTable.Routes);
  • BundleConfig.RegisterBundles(BundleTable.Bundles);

Order is very important (if i reverse areaRegistration with WebApiConfig => WebAPI 2 attributeRouting won't work



来源:https://stackoverflow.com/questions/31008197/webapi-2-attribute-routing-with-areas-not-working

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