2

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?

  • 1
    What is the detail error message? Have you configured `services.AddCors` in the second api project? You need to configure cors in the api which you want to send request to. – Edward Apr 18 '19 at 05:44

1 Answers1

2

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.

Martin
  • 14,189
  • 1
  • 26
  • 43