简体   繁体   English

NET Core Cors抛出错误

[英]NET Core Cors throws error

So I have the following: 所以我有以下内容:

public void ConfigureServices(IServiceCollection services)
{
    var corsBuilder = new CorsPolicyBuilder();
    corsBuilder.AllowAnyHeader();
    corsBuilder.AllowAnyMethod();
    corsBuilder.AllowAnyOrigin();
    corsBuilder.AllowCredentials();

    services.AddCors(options =>
    {
        options.AddPolicy("AllowAllOrigins", corsBuilder.Build());
    });

    services.AddDbContextPool<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddJsonOptions(
            options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );

    services.Configure<Infrastructure.FileOptions>(Configuration.GetSection("Files"));
    services.AddTransient<Infrastructure.ServiceCollection>();
}

As you can see I am allowing everyone to access my routes. 如你所见,我允许每个人访问我的路线。

However, when I try to access a route I get the following error: 但是,当我尝试访问路由时,我收到以下错误:

Failed to load https://localhost:44381/test : No 'Access-Control-Allow-Origin' header is present on the requested resource. 无法加载https:// localhost:44381 / test :请求的资源上没有“Access-Control-Allow-Origin”标头。 Origin ' http://localhost:4200 ' is therefore not allowed access. 因此不允许来源' http:// localhost:4200 '访问。

What have I done wrong? 我做错了什么?

You should add in the configure method this line 您应该在此行中添加configure方法

app.UseCors("AllowAllOrigins");

This activate the AllowAllOrigins that you configure in the services. 这将激活您在服务中配置的AllowAllOrigins

I faced the similar issue. 我遇到了类似的问题。 I tried it like this- 我试过这样 -

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

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors("CORSPolicy");
}

Also, if you host this on Azure, you need to do the CORS setting in Azure as well. 此外,如果您在Azure上托管此功能,则还需要在Azure中执行CORS设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM