I am getting below CORS errors for PUT and DELETE request only, GET and POST requests are working fine:

Access to XMLHttpRequest at 'https://localhost:444/api/...' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Background about my application: frontend is in React(next.js) and backend is in .NET 5. In backend project, I have already set the CORS policy to allow any header, method and specific origin but still now working. When I run the API project on IIS Express, it works but when I deployed it to IIS, it failed with above error.

Here are the CORS policy in .NET 5 project:

-- public void ConfigureServices(IServiceCollection services)

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder =>
                    {
                        builder
                          .AllowAnyHeader()
                          .AllowAnyMethod()
                          .WithOrigins("http://localhost:3000");
                    });

-- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

app.UseRouting();
app.UseCors();
app.UseAuthorization();

Here is the OPTIONS request for PUT:

**General:**
Request Method: OPTIONS
Status Code: 204 
Remote Address: [::1]:444
Referrer Policy: strict-origin-when-cross-origin
**Response Headers:**
access-control-allow-headers: content-type
access-control-allow-methods: PUT
access-control-allow-origin: *
date: Fri, 24 Sep 2021 01:49:11 GMT
server: Microsoft-IIS/10.0
x-powered-by: ASP.NET

Any idea?

4

There are 4 best solutions below

0
On

I believe when you deploy your code the client url will change from http://localhost:3000 to say [http://example.com/8080][1] Put this url in WithOrigins method -

-- public void ConfigureServices(IServiceCollection services)

        services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                    builder
                      .AllowAnyHeader()
                      .AllowAnyMethod()
                      ***.WithOrigins("http://example.com/8080");***
                });
0
On

I guess your problem is WebDAVModule is disabling PUT and DELETE methods. You must have below code block inside <system.webServer> in your web.config file just before <handlers> as below:

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

0
On

first you need to change the port you is using port 444 is reserved, by combention you need to start at port 3000, the first 2000 ports might be used by the OS. port 444 is free to use if

wikipedia says

Simple Network Paging Protocol (SNPP) is a protocol that defines a method by which a pager can receive a message over the Internet. It is supported by most major paging providers, and serves as an alternative to the paging modems used by many telecommunications services. The protocol was most recently described in RFC 1861. It is a fairly simple protocol that may run over TCP port 444 and sends out a page using only a handful of well-documented commands.

something else that will be helpful is if you have a CRA at yow package.json add a new prop call proxy and the url of yow back if you add it all your cors problems will desapear

"proxy": "http://localhost:8080"

and now all your fetches need to have a relative url

instead of

fetch("http://localhost:8080/api/login")

they have to be like

fetch("/api/login")

NOTICE: how the proxy prop at the package.json doesnot ends with an / and how them fetches do start with it / if you add that to your package you'll be able to add cookies and stuff. as the whole thing will be like if back and front had the same port

0
On

The problem is not with the CORS policy but the WebDAVModule in the web.config. If you try the PUT or DELETE request from browser or Postman, you'll get the 405 Not allowed error from the web server.

405-error-from-web-server

I have tried the same from the React app. I got the following response.

react-app-request-error

The console shows from origin 'http://localhost:9100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource., but the Network tab shows the error's status code is 405.

To fix this, you have to add the following configs in web.config.

     <modules>
        <remove name="WebDAVModule" />
     </modules>
      <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" />
      </handlers>

Even I have removed the port number from Startup class and added the following for CORS.

          // global cors policy
            app.UseCors(builder => builder
                .AllowAnyHeader()
                .AllowAnyMethod()
                .SetIsOriginAllowed((host) => true)
                .AllowCredentials()
            );

Please refer the .Net core application here and React app sandbox here.

Read more about the 405 method not allower error here