2015-06-23 46 views
0

在ASP.NET WebAPI中,我有一個可以使用GET動詞訪問的控制器/操作。如果我使用POST動詞查詢端點,我會得到一個標準的405 method not allowed響應。ASP.NET重寫'405方法不允許'http響應

是否可以攔截此行爲並注入我自己的自定義響應而不是那個沒有添加代碼的控制器?或者可能以某種方式覆蓋原始響應。這種行爲預計會出現在應用程序範圍內,因此我將不得不在全局範圍內設置此設置。

+0

瀏覽器不能發出POST請求。嘗試與提琴手或SOAP用戶界面 –

+0

這是正在測試與郵遞員可以發出POST請求。這些服務將來會被各種非瀏覽器客戶端使用。 – Vee6

回答

0

405的這種行爲是由管道尋找適當的控制器,然後通過命名約定或屬性的適當方法來確定的。我看到有兩種方法可以實現您的預​​期效果,即自定義IHttpActionSelector或基本ApiController。

爲IHttpActionSelector實施例的代碼:用於基本ApiController

public class CustomHttpActionSelector : IHttpActionSelector 
{ 
    public HttpActionDescriptor SelectAction(HttpControllerContext controllerContext) 
    { 
     var isPostSupported = false; 

     //logic to determine if you support the method or not 

     if (!isPostSupported) 
     { 
      //set any StatusCode and message here 
      var response = controllerContext.Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, "Overriding 405 here."); 
      throw new HttpResponseException(response); 
     } 
    } 

    ... 
} 

//add it to your HttpConfiguration (WebApiConfig.cs) 
config.Services.Add(typeof(IHttpActionSelector), new CustomHttpActionSelector()); 

示例代碼:

public abstract class BaseApiController<T> : ApiController 
{ 
    public virtual IHttpActionResult Post(T model) 
    { 
     //custom logic here for "overriding" the 405 response 
     return this.BadRequest(); 
    } 
} 

public class UsersController : BaseApiController<User> 
{ 
    public override IHttpActionResult(User model) 
    { 
     //do your real post here 
     return this.Ok(); 
    } 
}