其他项目中的Web Api控制器,路由属性不起作用 [英] Web Api Controller in other project, route attribute not working

查看:153
本文介绍了其他项目中的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).

这篇关于其他项目中的Web Api控制器,路由属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆