Asp.net-Mvc

路由屬性的Web Api 2全域路由前綴?

  • July 12, 2018

我想通過兩種方式公開公司的api:

  • api.company.com(純 WebApi 網站)
  • company.com/api(將 WebApi 添加到現有的 MVC5 公司站點)

因此,我將模型/控制器放在一個單獨的程序集中,並從兩個網站引用它。

另外,我使用路由屬性:

[RoutePrefix("products")]
public class ProductsController : ApiController

現在,可以通過以下方式訪問上面的控制器:

  • api.company.com/products哪個好
  • company.com/products我想更改為company.com/api/products

有沒有辦法繼續使用路由屬性並設置 MVC 項目,以便為所有路由添加“api”?

所以這可能不是你能做到的唯一方法,但我會這樣做:

  1. 創建您自己的繼承自 RoutePrefixAttribute 的屬性
  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;
   }
 }
}

編輯 (從 Web API 2.2 開始不再支持以下選項)

或者,您也可以指定多個路由前綴:

[RoutePrefix("api/products")]
[RoutePrefix("products")]
public class ProductsController : ApiController

引用自:https://stackoverflow.com/questions/22070559