0

In laravel or some express.js libs add middleware to check if a field is given called _Method which will override the actual http method of the http request on arrival of the server, because the browser only supports POST and GET.

Does ASP.NET (.NET Framework) contain a build-in middleware like those I just mentioned, I couldn't find anything online.

If so, how do I use it or do you know such an atricle.
If not, how can I create such a middleware myself.
I could not create one myself, because the HttpRequest in the HttpContext is readonly and the HttpMethod in the HttpRequest is readonly aswell.

Or is the only choice to use preventDefault() and/or ajax to send (for example) a DELETE request via javascript?

  • There are some in built modules on web server which prevents certain http verbs. In IIS that module is WebDAVModule. If this module is present in application running on IIS, DELETR web requests are blocked. So it needs to be removed from the application to allow DELETE requests. https://stackoverflow.com/questions/6147181/405-method-not-allowed-in-iis7-5-for-put-method – Chetan May 31 '20 at 01:41
  • https://ignas.me/tech/405-method-not-allowed-iis/ – Chetan May 31 '20 at 01:42
  • The delete api works fine, I tested it with postman. The question is about how I can access that api using browsers. – NS - Not the train May 31 '20 at 01:50
  • You can use Ajax for making API calls from browsers. – Chetan May 31 '20 at 01:57

2 Answers2

0

First of all, you need to assign [HttpDelete] attribute to your function in the controller or API. for example:

[HttpDelete]
public JsonResult MyDeleteFunction(int id)
{
    //Write your delete code here
    return Json("some responses");
}

Then in client-side, you can use ajax to do the delete request.

$.ajax({
    url: '/ControllerName/MyDeleteFunction',
    dataType: "json",
    type: "DELETE",
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({id: 123}),
    async: true,
    processData: false,
    cache: false,
    success: function (data) {
        alert(data);
    },
    error: function (xhr) {
        alert('error');
    }
});
BthGh
  • 192
  • 5
  • Thank you for your contribution, but I mentioned ajax in the question. I still am wondering if there is a middleware such as those mentioned in the question,if it is possible to make one yourself or whether ajax is the only way to go. – NS - Not the train May 31 '20 at 03:36
0

After some digging, I found that later in the chain of ASP.NET the HttpContext Changes into HttpContextBase. This context contains GetHttpMethodOverride().
I looked the Method up on github, because it's open source and ASP.NET does contain a middleware such as mentioned.
You can override the actual http method using the key X-HTTP-Method-Override in either the Header, Form or Query string and the actual http method must be POST for the middleware to even consider a http method override.