Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 388
user1613512 Avatar asked Mar 18 '14 09:03

user1613512


People also ask

Which attribute is used to define routes in Web API?

Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API. For example, you can easily create URIs that describe hierarchies of resources.

Which code segment should you use to enable attribute routing?

To enable attribute routing, call MapHttpAttributeRoutes during configuration. This extension method is defined in the System. Web. Http.

Is convention routing and attribute routing can work together?

Note: Attribute Routing is configuring before the Convention Routing or simple Routing. We can use Convention based Routing and Attribute Routing in the same project. Be sure attribute routing should be defined first to convention based routing.


2 Answers

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

like image 91
Darrel Miller Avatar answered Oct 24 '22 16:10

Darrel Miller


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.

like image 32
Mike4QL Avatar answered Oct 24 '22 17:10

Mike4QL