Web Api Controller in other project, route attribute not working

旧街凉风 提交于 2019-12-03 23:12:13
Darrel Miller

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

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