Question

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?

Was it helpful?

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).

OTHER TIPS

One possibility is you have 2 routes on different controllers with the same name.

I had 2 controllers both named "UploadController", each in a different namespace and each decorated with a different [RoutePrefix()]. When I tried to access either route I got a 404.

It started working when I changed the name of one of the controllers. It seems the Route Attribute is only keyed on the class name and ignores the namespace.

We were trying to solve a similar problem. The routes within the external assembly were not registering correctly. We found one additional detail when trying the solution shown on this page. The call to the external assembly "MyApiConfig.Register" needed to come before the call to MapHttpRoute

HttpConfiguration config = new HttpConfiguration();
MyExternalNamespace.MyApiConfig.Register(config); //This needs to be before the call to "config.Routes.MapHttpRoute(..."
config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top