Home > Back-end >  Applying CORS on ASP.NET Core 1.1 not working as expected
Applying CORS on ASP.NET Core 1.1 not working as expected

Time:01-24

On ASP.NET Core 1.1.

I included the nuget package Microsoft.AspNetCore.Cors" Version="1.1.2.

Startup.cs has CORS code shown below.

These are the issues:

  • Issue 1: as per the below code CORS has been configured to allow only 'POST' but it allows ALL http methods not restricting only to 'POST'

  • Issue 2: CORS has been configured only to allow "CustomHeader1", "CustomHeader2" but NOT allowing any request headers including valid "CustomHeader1", "CustomHeader2" request headers. If I remove headers altogether in the request then only receiving response.

Code:

 public IServiceProvider ConfigureServices(IServiceCollection services)
 {
     services.AddCors();
 }

 public void Configure(IApplicationBuilder app)
 {
     app.UseCors(builder => builder
                                .AllowAnyOrigin()
                                .WithMethods("POST")
                                .WithHeaders("CustomHeader1", "CustomHeader2")
                );
 }

What I'm missing to configure CORS only for POST method & to allow only "CustomHeader1", "CustomHeader2" in the request?

CodePudding user response:

you can try this syntax

public void ConfigureServices(IServiceCollection services)
{
            ....
            services.AddCors(o => o.AddPolicy("AllowAnyOrigin", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));

             .....
}

public void Configure(IApplicationBuilder app)
{
            ....

            app.UseRouting();   
            app.UseCors("AllowAnyOrigin");
            //app.UseAuthentication();
            //app.UseAuthorization();
           ....
}

CodePudding user response:

In .Net-Core 1.1, you need add

app.UseCors(builder => builder
    .AllowAnyOrigin()
    .WithMethods("POST")
    .WithHeaders("CustomHeader1", "CustomHeader2")
);

before calling app.UseMvc() and app.UseStaticFiles().


Suggestion 1 :

If your webapp is hosting on IIS, please check this link. If you are in the development stage, please the order in your Startup.cs file.

Suggestion 2 :

If it still not work, please generate publish file and check if there is a web.config file generated.

Suggestion 3 :

It is recommended to code according to the official examples, the official codes are all tested and can save a lot of time.

  •  Tags:  
  • Related