Web Api Controller in other project, route attribute not working

风流意气都作罢 提交于 2019-12-05 13:51:46

问题


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?


回答1:


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




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/22474982/web-api-controller-in-other-project-route-attribute-not-working

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