CORS Error in Core and React when hosting in IIS

Viewed 414

Working on React + ASP.net Core, works fine on local host, When i hosted in IIS server, I am getting CORS error.

"Access to fetch at 'http://10.100.221.6:9037/authentication' from origin 'http://10.100.221.6:9039' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

Here http://10.100.221.6:9037/authentication is my ASP.net Core application hosted in port 9037

http://10.100.221.6:9039 is my react application in port 9039

Following things already tried

  1. Launch setting i have added URL in ASP.net Core "ReactWindowsAuth": { "commandName": "Project", "launchBrowser": true, "launchUrl": "weatherforecast", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "applicationUrl": "https://localhost:5001;http://localhost:5000; http://10.100.221.6:9039" }, "Docker": { "commandName": "Docker", "launchBrowser": true, "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/weatherforecast", "publishAllPorts": true, "useSSL": true } } }

  2. In appsetting, included CORS "AllowedHosts": "*", "CorsOrigins": [ "http://localhost:3000", "http://10.100.221.6:9039" ],

  3. In react application also, Authentication-api added api

     const apiBase = "http://10.100.221.6:9037/authentication";
    
     class AuthenticationService {
     getRoles() {
     let request = Object.assign({}, requestBase, { method: "GET" });
     let url = `${apiBase}`;
     return fetch(url, request).then(handleResponse);
     }
     }
    
1 Answers

You can enable CORS On the ASP.NET Core side.

var  MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      builder =>
                      {
                          builder.WithOrigins("http://example.com",
                                              "http://www.contoso.com");
                      });
});

// services.AddResponseCaching();

builder.Services.AddControllers();

var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthorization();

app.MapControllers();

app.Run();

You can refer Microsoft document

Related