其他项目中的Web Api控制器,路由属性不起作用

其他项目中的Web Api控制器,路由属性不起作用

问题描述:

我有两个项目的解决方案.一个Web Api引导项目,另一个是类库.

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

类库包含带有属性路由的ApiController. 我将来自Web api项目的引用添加到类库,并希望它能正常工作.

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.

已配置Web api中的路由:

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

但是当我进入网址"/alert"时得到了404.

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.

有什么想法吗?

尝试一下.在您的类库项目中创建一个如下所示的类,

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

以及您当前正在呼叫config.MapHttpAttributeRoutes()的任何地方,请致电MyApiConfig.Register(config).

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