Search code examples
c#asp.net-web-apiasp.net-web-api2asp.net-web-api-routingattributerouting

Web Api Controller in other project, route attribute not working


I have a solution with two projects. One Web Api bootstap project and the other is a class library.

The class library contains a ApiController with attribute routing. I add a reference from web api project to the class library and expect this to just work.

The routing in the web api is configured:

config.MapHttpAttributeRoutes();

The controller is simple and looks like:

public class AlertApiController:ApiController
{
    [Route("alert")]
    [HttpGet]
    public HttpResponseMessage GetAlert()
    {
        return Request.CreateResponse<string>(HttpStatusCode.OK,  "alert");
    }
}

But I get a 404 when going to the url "/alert".

What am I missing here? Why can't I use this controller? The assembly is definitely loaded so I don't think http://www.strathweb.com/2012/06/using-controllers-from-an-external-assembly-in-asp-net-web-api/ is the answer here.

Any ideas?


Solution

  • Try this. Create a class in your class library project that looks like this,

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

    And wherever you are currently calling the config.MapHttpAttributeRoutes(), instead call MyApiConfig.Register(config).