Question

I'm experimenting with ASP.Net Web API, which, by convention, splits controller methods into a Restful style of Get(), Put, Post and Delete. My question is how does one handle the PUT and DELETE requests that might come from a non-Ajax browser request.

So, let's say that I have foobar with id = 123. A normal fetch request would be

/foobars/123

To delete the item, the Restful way would be to issue:

DELETE /foobars/123

However, PUT and DELETE are not browser standards and do not have enough major browser support to be trusted if your request is coming from a non-Ajax browser request. So a common accepted workaround is:

POST /foobars/123?_method=DELETE (source: Restful Web Services)

For the new ASP.Net Web API, is there a best practice / common approach for working with this problem? What I want is for anything with a _method=DELETE to be routed to the DELETE() method in the controller and _method=PUT to be routed to the PUT() method of a controller.

Was it helpful?

Solution

You can easily achieve this using a DelegatingHandler.

So you would code:

public class HttpMethodHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var queryString = HttpUtility.ParseQueryString(request.RequestUri.Query);
        if(!string.IsNullOrEmpty(queryString["_method"]))
        {
            request.Method = new HttpMethod(queryString["_method"]);
        }
        return base.SendAsync(request, cancellationToken);
    }
}

And then add the handler to the pipeline. I have a blog on that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top