簡體   English   中英

如何禁用ASP.NET Web API的動詞

[英]How do I disable verbs for ASP.NET Web API

我需要在控制器上禁用POST,PUT和DELETE動詞。 我目前正在返回MethodNotAllowed ,如下所示,但我覺得必須有更好的方法。 我懷疑有可以添加到Web api管道的過濾器,但是我不確定我需要什么或在哪里進行過濾。

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

如何在不放置代碼的情況下阻止某些動詞,而不為控制器中每個不允許的方法返回HttpResponseMessage 很高興收到,仍然返回相應的http狀態代碼。

可以禁用屬性路由HTTP方法中允許的動詞,而不是禁用不允許的動詞。

要僅允許對您的方法進行POST,請在方法[HttpPost]定義[HttpPost]

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

Web Api 2中包含的不同類型的HTTP方法

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

您可以在此鏈接的“ HTTP方法”部分中閱讀有關它們的內容。

實現一個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")]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM