2016-12-13 55 views
0

我需要在我的控制器上禁用POST,PUT和DELETE動詞。我目前正在返回MethodNotAllowed,如下所示,但我覺得必須有更好的方法。我懷疑有一個過濾器可以添加到Web API管道中,但我不確定我需要什麼或在哪裏做。如何禁用ASP.NET Web API的動詞

public HttpResponseMessage Post([FromBody]string value) 
    { 
     return new HttpResponseMessage(HttpStatusCode.MethodNotAllowed); 
    } 

我如何阻止某些動詞沒有放置代碼,以在控制器每個不允許方法返回一個HttpResponseMessage?很高興,仍然返回相應的http狀態碼。

+1

全部一起移除所有操作。框架使用約定來查找匹配請求的操作。你的控制器是否定義了這些動詞? – Nkosi

回答

0

實現一個ActionFilterAttribute

public class CustomAttribute: ActionFilterAttribute 
    { 
     public CustomAttribute() 
     { 

     } 

     public string AllowVerbs { get; set; } 

     public string DenyVerbs { get; set; } 

     public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) 
     { 
      //get the verb 
      var verb = actionContext.Request.Method; 

      //check the verb based on AllowVerbs, DenyVerbs 

      //set your response here if not allowed 
      //actionContext.Response = response; 
     } 
    } 

然後標記與

[Custom(DenyVerbs="PUT,POST,DELETE")] 
0

控制器而不是禁止說不準,你可以定義被允許與屬性路線HTTP方法動詞的動詞。

爲只允許張貼到您的方法,定義[httpPost]盈方法

[httpPost] 
public HttpResponseMessage Post([FromBody]string value) 
{ 
    return new HttpResponseMessage(HttpStatusCode.MethodNotAllowed); 
} 

不同類型的HTTP方法中包含的網頁API 2

[HttpDelete] 
[HttpGet] 
[HttpHead] 
[HttpOptions] 
[HttpPatch] 
[HttpPost] 
[HttpPut] 

你可以閱讀他們微塵在這個link的HTTP方法部分