robdigm
robdigm

Reputation: 143

.NET 6 CORS policy blocked on Client side CORS

The client-side of my application is.NET6 and server-side web API is .NET 4.8. When attempting to access server-side the following error is produced within the console of the browser:

Access to fetch at 'https://localhost:12345/api/controller/method' from origin 'https://localhost:34564' has been blocked by CORS policy: 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.

Within my startup.cs I have the following code:

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

    // In production, the React files will be served from this directory
    services.AddSpaStaticFiles(configuration =>
    {
        configuration.RootPath = "ClientApp/build";
    });
    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigin",
            builder => builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader()
        );

    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();               
    }
    else
    {  
        app.UseHsts();
    }
    app.UseCors("AllowSpecificOrigin");
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseSpaStaticFiles();
    app.UseRouting();
    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";

        if (env.IsDevelopment())
        {
            spa.UseReactDevelopmentServer(npmScript: "start");
        }
    });
}

CORS setting in 'WebAPIConfig.cs

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
            config.Filters.Add(new AuthorizationAttribute());
            config.MapHttpAttributeRoutes();
            // Web API routes
            GlobalConfiguration.Configuration.Formatters.Add(new FormMultipartEncodedMediaTypeFormatter());
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}/{other}",
                defaults: new { id = RouteParameter.Optional, other = RouteParameter.Optional }
            );            
        }
    }

Upvotes: 2

Views: 10936

Answers (2)

Rahul Sharma
Rahul Sharma

Reputation: 8311

In order to resolve your CORS issue, you can do the following in your web.config file:

Under <system.webServer> section, place the following to enable CORS globally in your project:

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Credentials" value="true"/>
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, OPTIONS" />
    </customHeaders>
</httpProtocol>

Upvotes: 3

Marko
Marko

Reputation: 13263

I'm not sure why "AllowAnyOrigin()" does not work but I managed to bypass the issue with this code:

// global cors policy
app.UseCors(x => x
    .AllowAnyMethod()
    .AllowAnyHeader()
    .SetIsOriginAllowed(origin => true) // allow any origin 
    .AllowCredentials());

And of course this needs to be in your API project code not the front end code.

Upvotes: 10

Related Questions