Web Api 2路由属性的全局路由前缀?

mt_*_*erg 14 asp.net-mvc asp.net-web-api asp.net-web-api-routing

我想通过两种方式揭露公司的api:

  • api.company.com(纯WebApi网站)

  • company.com/api(将WebApi添加到现有的MVC5公司站点)

因此,我将模型/控制器放在一个单独的程序集中,并从两个网站引用它.

另外,我使用路由属性:

[RoutePrefix("products")]
public class ProductsController : ApiController
Run Code Online (Sandbox Code Playgroud)

现在,上面的控制器可以通过以下方式访问:

  • api.company.com/products哪个好

  • company.com/products我想更改为company.com/api/products

有没有办法继续使用路由属性和设置MVC项目,所以它为所有路由添加"api"?

Rei*_*las 9

所以这可能不是你能做到的唯一方法,但这就是我要做的:

  1. 创建自己的继承自RoutePrefixAttribute的Attribute
  2. 如果在所需的服务器上运行,则覆盖Prefix属性并在其中添加一些逻辑以在前缀之前添加"api".
  3. 根据web.config中的设置,预先添加到路由.

    public class CustomRoutePrefixAttribute : RoutePrefixAttribute
    {
    
      public CustomRoutePrefixAttribute(string prefix) : base(prefix)
      {
      }
    
      public override string Prefix
      {
        get
        {
            if (Configuration.PrependApi)
            {
                return "api/" + base.Prefix;
            }
    
            return base.Prefix;
        }
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)

编辑 (从Web API 2.2开始不再支持以下选项)

或者,您也可以指定多个路由前缀:

[RoutePrefix("api/products")]
[RoutePrefix("products")]
public class ProductsController : ApiController
Run Code Online (Sandbox Code Playgroud)

  • 请注意,添加重复的`RoutePrefix`属性现在会抛出编译器错误(Web API 2.2) (5认同)

小智 6

您可以在IAppBuilder上使用Map

所以Startup类看起来像这样

class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Map("/api", map =>
        {
            HttpConfiguration config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            map.UseWebApi(config);
        });

    }
}
Run Code Online (Sandbox Code Playgroud)