2016-12-13 52 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方法部分