Search code examples
asp.net-mvc-4asp.net-web-apiasp.net-mvc-5attributerouting

Attribute Routing in WebAPI: The Resource Cannot Be Found


ASP.NET MVC4 Project with WebAPI endpoints. I'm trying to configure AR for both MVC Controllers and API controllers. I added the following:

enter image description here

And now I see two more files in App_Start: AttributeRoutingConfig, and AttributeRoutingHttpConfig.

The first has this:

[assembly: WebActivator.PreApplicationStartMethod(typeof(AttributeRoutingConfig), "Start")]

public static class AttributeRoutingConfig
{
    public static void RegisterRoutes(RouteCollection routes) 
    {       
        GlobalConfiguration.Configuration.Routes.MapHttpAttributeRoutes();
    }
    public static void Start() 
    {
        RegisterRoutes(RouteTable.Routes);
    }
}

The second has this:

[assembly: WebActivator.PreApplicationStartMethod(typeof(AttributeRoutingHttpConfig), "Start")]

public static class AttributeRoutingHttpConfig
{
    public static void RegisterRoutes(HttpRouteCollection routes) 
    {    
        routes.MapHttpAttributeRoutes();
    }
    public static void Start() 
    {
        RegisterRoutes(GlobalConfiguration.Configuration.Routes);
    }
}

In my GlobalConfig I have this:

 GlobalConfiguration.Configure(WebApiConfig.Register);

In my WebApiConfig I have this:

 config.MapHttpAttributeRoutes();

The error I get when I try to POST to a route decorated with [POST("api/message")]:

The constraint entry 'inboundHttpMethod' on the route with route template 'api/message' must have a string value or be of a type which implements 'IHttpRouteConstraint'.

In my Global.asax:

        GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

What am I doing wrong?


Solution

  • You are trying to combine Tim McCall's package + Web API 2's built-in Attribute routing feature. Do not install the package as its already built into Web API 2 version.

    Check this: http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2