Search code examples
c#.net-corecorspreflight

CORS policy - response to preflight request


I am setting up the CORS policy in my .NET Core 3.1 web app but I am getting an error that says

Access to XMLHttpRequest at 'http://10.10.100.60/api/api/values/getmyorders?toOrder=false&uId=8c3d745b-78b7-47ed-ac93-310fe61b8daf' from origin 'http://10.10.100.66:8080' 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.

I have previously never encountered this preflight error. Here's what my Startup looks like

public void ConfigureServices(IServiceCollection services)
        {
         //code shortened for brevity
         services.AddCors();
        }

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddProvider(new Log4NetProvider("log4net.config", true));
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());

            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseMvc();
        }

I also tried using other CORS methods like the CORS with named policy and middleware as well as the default policy but I still get the same preflight error. Any suggestion on how do I proceed?


Solution

  • Here's what worked for me several hours later.

    public void ConfigureServices(IServiceCollection services)
            {
                services.AddCors(options =>
                {
                    options.AddPolicy("AllowAllHeaders",
                    builder =>
                    {
                        builder.AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                    });
                });
            }
    
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
                app.UseCors("AllowAllHeaders");
                app.UseAuthentication();
                app.UseHttpsRedirection();
                app.UseMvc();
            }
    

    I am now only using the AllowAnyOrigin(), AllowAnyHeader() and the AllowAnyMethod(). I assume there was an issue with the AllowCredentials(). Hopefully this answer helps someone in the future.