2

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 }
            );            
        }
    }
robdigm
  • 143
  • 2
  • 16
  • 2
    CORS is a server-side responsibility. You need to configure it in your API service (`localhost:12345`) – Phil Jan 10 '22 at 22:45
  • @Phil since the server-side is .NET 4.8, where exactly would I insert this configuration? – robdigm Jan 10 '22 at 22:50
  • @Phil I actually have this in the WebAPI already. Let me update the question. – robdigm Jan 10 '22 at 23:17
  • @RahulSharma It didn't but I think the issue is much deeper than I think. Thank you for your help regardless. – robdigm Jan 12 '22 at 16:12

2 Answers2

9

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.

Marko
  • 12,543
  • 10
  • 48
  • 58
  • my backend is .Net4.8 and does not have a startup.cs. However, I have a webConfigAPI – robdigm Jan 10 '22 at 23:59
  • this worked for me, .net core 6.0 webapi, react front-end... thks! – MX313 Nov 14 '22 at 20:41
  • this is a great answer I spent almost one week trying to solve it and never find a solution I do not know as well what is the reason to have 2 methods with the same functionality name one of them working and the other just watching you suffering THANK YOU SO MUCH – moath naji Jul 03 '23 at 13:03
3

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>
Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54