0

I need to disable POST, PUT and DELETE verbs on my controllers. I'm currently returning a MethodNotAllowed as shown below but I feel there must be a better way. I suspect there is a filter I can add to the web api pipeline but I'm not sure what I need or where to do it.

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

How do I block certain verbs without placing code to return a HttpResponseMessage for each disallowed method in a controller? Nice to have, still return the appropriate http status code.

1
  • 1
    remove the actions all together. framework uses conventions to find actions that match request made. Do your controllers have those verbs defined Commented Dec 13, 2016 at 19:02

2 Answers 2

1

Instead of disable the verbs that are not allowed you could define the verbs that are allowed with the attribute routings HTTP Methods.

To only allow POST to your method, define [HttpPost] infront of the method

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

The different types of HTTP Methods included in Web Api 2

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

You can read mote about them in the HTTP Methods section in this link

Sign up to request clarification or add additional context in comments.

Comments

0

Implement an 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;
        }
    }

Then mark your controller with

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.