Search code examples
c#iisasp.net-corehttp-status-code-405

Getting 405 error when making a DELETE request from an asp.net core app


I have an asp.net core API, from which I am trying to make a DELETE request to another asp.net core API. When I call the first API I receive a 405 error when it makes the delete call to the second API. I've tried the solution found here; ASP.NET Core with IIS - HTTP Verb Not Allowed, and several other related solutions without success. I've also tried Enabling Cross-Origin Requests (CORS) in my Startup.cs file, however nothing seemed to change.

Here is my delete endpoint:

    [HttpDelete("MyDeleteEndpoint")]
    public async Task MyDeleteEndpoint([FromRoute] string id)
    {
        var http = new HttpClient();

        var response = await http.DeleteAsync("https://myserver:443/api/mycontroller/{id});

        //do more stuff
    }    

Here is my web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="false">
      <remove name="WebDAVModule" />
    </modules>
  </system.webServer>
</configuration>  

Here is my ConfigureServices and my Configure methods in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

  services.AddCors(options =>
  {
      options.AddPolicy("mypolicy",
      builder =>
      {
          builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
      });
  });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
         app.UseHsts();
    }

    app.UseCors("mypolicy");
    app.UseHttpsRedirection();
    app.UseMvc();
}

Any ideas on what I could be doing wrong?


Solution

  • I've had this problem before. The only way to resolve it that I found was to explicitly list the methods that were allowed in the web.config.

    Here is an excerpt from the web.config. Note that you probably don't want all of these settings but I'm leaving them in for brevity:

    ...
    <httpProtocol>
      <customHeaders>
        <remove name="X-Powered-By" />
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Credentials" value="true" />
        <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
        <add name="Access-Control-Allow-Headers" value="authorization,content-type" />
      </customHeaders>
    </httpProtocol>
    ...
    

    Without explicitly adding the DELETE request to the allowed methods, the request was automatically rejected before it even got to my code.