WebAPI Delete not working - 405 Method Not Allowed
Asked Answered
T

15

136

I appreciate any help on this as the site is supposed to go live tonight!

I have a web api controller with a Delete method. The method executes fine on my local machine running IIS Express (Windows 8) but as soon as I deployed it to the live IIS server (Windows Server 2008 R2) it stopped working and throws the following error message:

HTTP Error 405.0 - Method Not Allowed The page you are looking for cannot be displayed because an invalid method (HTTP Verb) is being used

I have looked around the web for solutions and I implemented most reasonable ones. My web config has the following settings:

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
<handlers>
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>

I have also tried to change the Handler Mappings and Request Filtering in IIS to no avail. Please note that the WebDAV Authoring Rules in IIS seems to be disabled.

Any ideas will be greatly appreciated Thanks.

Tamaratamarack answered 25/3, 2013 at 15:47 Comment(0)
T
228

I found the solution eventually! If you come across the same issue, add the following to your web.config

<system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true">
        <remove name="WebDAVModule"/> <!-- ADD THIS -->
    </modules>
    ... rest of settings here
Tamaratamarack answered 25/3, 2013 at 16:5 Comment(8)
I also had to add a remove in the handlers section as per https://mcmap.net/q/76712/-how-can-i-get-odata-delete-to-workNictitate
Also worked here. But can someone explain me the relation to WebDAVModule?Slinkman
for those who just copy-paste: runAllManagedModulesForAllRequests="true" is not really needed and can actually break other things.Jo
Some other web posts will suggest removing the module using IIS Modules section, this disables it but it still causes this/a similar problem, this is the most reliable methodCharinile
Thanks for your answer, but unfortunately it didn't worked for me (I'm using IIS 7.5). After 2 days of research, the only working solution I found to avoid "405 Method Not Allowed" was to define the CORS headers in the Application_BeginRequest method, as mentioned in this answer https://mcmap.net/q/74256/-enabling-cross-origin-resource-sharing-on-iis7Pleiades
@ZarShardan (and others) FYI: If you remove the runAllManagedModulesForAllRequests="true" attribute you will also need to add <remove name="WebDAV" /> under the <handlers> node as well.Regurgitate
You can also perform this operation from ISS manager (Modules and then Handlers - remove WebDAV).Fleeman
I ended up uninstalling the WebDAV feature to get this to work. Removing the module in config did not work for me.Microseism
P
75

In some cases removing it just from modules can produce next error:

500.21 Handler "WebDAV" has a bad module "WebDAVModule" in its module list

Module: IIS Web Core Notification: ExecuteRequestHandler"

solution was suggested here. Also need to remove it from handlers.

<system.webServer>
    <modules>
        <remove name="WebDAVModule" />
    </modules>
    <handlers>
        <remove name="WebDAV" />
    </handlers>
</system.webServer>
Pedate answered 22/9, 2014 at 12:58 Comment(0)
T
38

In my case none of the above solutions worked. This was because I had changed the name of the parameter in my Delete method.

I had

public void Delete(string Questionid)

instead of

public void Delete(string id)

I need to use the id name because that's the name that is declared in my WebApiConfig file. Note the id name in the third and fourth lines:

            config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

I got this solution from here.

Telling answered 13/3, 2015 at 10:12 Comment(1)
In my case I had defined [Route(...)] with a different parameter name to the actual method.Displume
U
15

The Javascript for HTTP DELETE verb must be like this:

$.ajax({
    **url: "/api/SomeController/" + id,**
    type: "DELETE",
    dataType: "json",
    success: function(data, statusText) {
        alert(data);
    },
    error: function(request, textStatus, error) {
        alert(error);
        debugger;
    }
});

Do not use something like this:

...
data: {id:id}
...

as when you use the POST method.

Ungulate answered 16/4, 2015 at 7:54 Comment(1)
Hi @Pavel, this is correct if you're indeed using a fully RESTful implementation. Unfortunately, not everyone does this and it's quite common to see developers using POST instead of DELETE etc. Thanks for clarifying this.Tamaratamarack
R
10

If you are using IIS 7.0 or later version. This issue is mainly related to WebDAV extension module on IIS server. this happened while Using Post OR delete action.

Please try below setting in web config

<system.webServer>
   <modules>
       <remove name="WebDAVModule" />
   </modules>
   <handlers>
     <remove name="WebDAV" />
   </handlers>
</system.webServer>
Rebato answered 20/3, 2020 at 10:10 Comment(0)
C
9

After trying almost every solutions here this worked for me. Add this in your APIs config file

<system.webServer>
    <handlers>
      <remove name="WebDAV" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <modules>
        <remove name="WebDAVModule" />
    </modules>
</system.webServer>
Cantata answered 20/12, 2017 at 13:51 Comment(0)
N
4

Go to applicationHost.config (usually under C:\Windows\System32\inetsrv\config) file and comment out the following line in applicationHost.config

1)Under <handlers>:

<add name="WebDAV" path="*" verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK" modules="WebDAVModule" resourceType="Unspecified" requireAccess="None" />

2)Also comment out the following module being referred by the above handler under <modules>

<add name="WebDAVModule" />
Nisen answered 8/1, 2016 at 11:59 Comment(1)
Or use the other answer https://mcmap.net/q/76284/-webapi-delete-not-working-405-method-not-allowed to REMOVE these handlers in your own web.config, if you don't want to (or can't) modify the machine-wide config fileSeka
J
3

I also had the same problem, I am calling WebAPi and is getting this error. Adding following configuration in web.config for services solved my problem

    <modules runAllManagedModulesForAllRequests="true">
        <remove name="WebDAVModule"/> <!-- add this -->
    </modules>

in web.config file solved my problem. This is How i was calling from client side

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(environment.ServiceUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    HttpResponseMessage response = client.DeleteAsync("api/Producer/" + _nopProducerId).Result;
    if (response.IsSuccessStatusCode)
    {
        string strResult = response.Content.ReadAsAsync<string>().Result;
    }
}
Jaf answered 20/5, 2015 at 2:1 Comment(0)
R
2

In my case, I missed to add {id} to the [Route("")] and I got the same error. Adding that fixed the problem for me: [Route("{id}")]

Reticular answered 5/4, 2019 at 6:10 Comment(0)
R
1

I had 405 error Method Not Allowed because I had omitted to make the Delete method on the WebApi controller public.

It took me a long time to find this (too long!) because I would have expected a Not Found error in this case, so I was incorrectly assuming that my Delete method was being denied.

The reason for Not Allowed rather than Not Found is that I also had a Get method for the same route (which will be the normal case when implementing REST). The public Get function is matched by the routing and then denied because of the wrong http method.

A simple error I know but it may save someone else some time.

Ringo answered 24/3, 2016 at 12:19 Comment(0)
M
1

Just to add. If this is your config

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }

please keep doing as Hugo said, and do not set Route attribute to the controller get method, this gave a problem in my case.

Manny answered 24/4, 2016 at 9:42 Comment(0)
U
1

I had the similar issue but for PUT - none of the other suggestions worked for me.

However i was using int rather than the default string for the id. adding {id:int} to the route solved my problem.

    [Route("api/Project/{id:int}")]
    public async Task<IHttpActionResult> Put(int id, [FromBody]EditProjectCommand value)
    {
       ...
    }
Upsilon answered 20/6, 2016 at 12:24 Comment(0)
T
1

I am working on .Net 5 Api project, and adding :

    <modules>
        <remove name="WebDAVModule" />
    </modules>

to the <system.webServer> part of web.config and

  <handlers>
        <remove name="WebDAV" />
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,PUT,DELETE,DEBUG" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0" />
        
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
  </handlers>

fixed it for me.

However, tricky part was making this work in the Azure DevOps CI-CD pipelines.
I managed to do it, and spoke about how I did it here: Azure DevOps Release Pipeline Web.Config Edit

Tripos answered 15/8, 2022 at 13:1 Comment(1)
I am working with .NET 6 API and MVC dumped this code inside both web.config files and it is working now. Thank you!Indefensible
G
0

We had to add custom headers to our web.config as our request had multiple headers that confused the API response.

<httpProtocol>
    <customHeaders>
        <remove name="Access-Control-Allow-Methods" />
        <remove name="Access-Control-Allow-Origin" />
        <remove name="Access-Control-Allow-Headers" />
    </customHeaders>
</httpProtocol>
Godding answered 31/3, 2017 at 20:47 Comment(0)
I
-4

[HttpPost] attribute on the top of Delete method solved this issue for me:

[HttpPost]
public void Delete(int Id)
{
  //Delete logic
}
Innis answered 26/1, 2015 at 7:54 Comment(4)
That could be a reason why it's working for you. I was on an earlier version, circa early 2013, so quite a few things have been fixed since. Glad to know it's working for you though.Tamaratamarack
This isn't a good answer to be honest. The people whose problem was resolved using this are using POST instead of DELETE so it couldn't and shouldn't workUnemployed
I believe this is because you are using data (i.e. the body of the request) instead of params (i.e. the url of the request) in the client side.Amenable
I agree with Alexander Derck, this is a kludge rather than a solution.Effectual

© 2022 - 2024 — McMap. All rights reserved.