Search code examples
c#.netasp.net-corecorspreflight

How to fix CORS error: MethodDisallowedByPreflightResponse in ASP .NET C#


The Problem

Sending an http request to an ASP.NET Core API server (although I believe this will apply to a variety of different .NET style servers) I get the CORS error: MethodDisallowedByPreflightResponse. I specifically am getting this error on a PUT request (it does not occur on POST or GET requests).

What I tried:

  • Googling, no one else has written about this specific error.
  • DevTools Network tab (ie. inspecting the actual Http request headers and content)... There is nothing in the preflight request/response that seems to indicate anything about which methods are allowed and which aren't.

Solution

  • My Answer:

    Looking at my server's CORS settings, I realized that the .AllowAnyHeader() method on the Cors middleware might indicate there is a similar method for allowing any Methods. I was correct.

    Use .AllowAnyMethod() to fix this error (assuming you actually want to allow any http method type).

    Here is where you specifically put this on your server (I'm using ASP.NET CORE API, version 5 I believe) :

    //Startup.cs
    
    //.... in the "Startup" class "ConfigureServices" method....
    public void ConfigureServices(IServiceCollection services)
            {
                services.AddCors(options =>
                {
                    options.AddDefaultPolicy(
                        builder =>
                        {
                            builder.WithOrigins("https://example.com")
                                .AllowAnyHeader()
                                .AllowAnyMethod(); //THIS LINE RIGHT HERE IS WHAT YOU NEED
                        });
                });
    
    // ... the rest of your code, other middleware, etc.