.NET technology -4.0. NETCORE cross-domain

.NET technology -4.0. NETCORE cross-domain

 

1. CORS installer package, all with a general default for this package

Install-Package Microsoft.AspNetCore.Mvc.Cors

 

Configuring CORS Service

In the  Startupclass, ConfigureServicesmethod, the add the following code:

services.AddCors(option=>option.AddPolicy("cors", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowCredentials().AllowAnyOrigin()));

    //例:
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddCors(option => option.AddPolicy("cors", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowCredentials().AllowAnyOrigin())); }

 

Policy name can define their own

 

 

Be sure to pay attention to see the following:

The new version of CORS has prevented the use of middleware allows arbitrary Origin, that is  AllowAnyOrigin set up, it will not take effect.

 

Solution: Use  WithOrigins to set Origin

example:

policy.AllowAnyHeader().AllowAnyMethod().AllowCredentials().WithOrigins(new []{"http://xxx.xxx.com"});

 

 

3. Configure CORS middleware

In the  Startupclass, Configuremethod, the add the following code:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseCors("cors");
    app.UseMvc();
}

 

 

Mainly  app.UseCors("cors");this code, note that must be placed  UseMvc before, and the policy name must have been defined .

 

carry out.

 

 

 

 

 

 

 

Quote: https://www.cnblogs.com/stulzq/p/9392150.html

 

Guess you like

Origin www.cnblogs.com/1285026182YUAN/p/11348911.html