我正在尝试在我的ASP上启用跨起源资源共享。NET核心Web API,但我卡住了。

EnableCors属性接受字符串类型的policyName作为参数:

// Summary:
//     Creates a new instance of the Microsoft.AspNetCore.Cors.Core.EnableCorsAttribute.
//
// Parameters:
//   policyName:
//     The name of the policy to be applied.
public EnableCorsAttribute(string policyName);

policyName是什么意思,如何在ASP上配置CORS。NET核心Web API?


当前回答

你必须在Startup.cs类中进行配置

services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });

其他回答

如果你得到错误“没有'Access-Control-Allow-Origin'头是存在于所请求的资源。”特别是对于PUT和DELETE请求,您可以尝试在IIS上禁用WebDAV。

显然,WebDAVModule默认启用,默认禁用PUT和DELETE请求。

禁用WebDAVModule,添加到你的web.config:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="false">
    <remove name="WebDAVModule" />
  </modules>
</system.webServer>

你有三种方式启用CORS:

在中间件中使用命名策略或默认策略。 使用端点路由。 使用[EnableCors]属性。

启用指定策略的CORS:

public class Startup
{
    readonly string CorsPolicy = "_corsPolicy";

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: CorsPolicy,
                              builder =>
                              {
                                 builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      .AllowCredentials();
                              });
        });

        // services.AddResponseCaching();
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors(CorsPolicy);

        // app.UseResponseCaching();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

当使用UseResponseCaching时,UseCors必须在UseResponseCaching之前调用。

开启默认策略下的CORS:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                     builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      .AllowCredentials();
                });
        });

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

启用带有端点的CORS

public class Startup
{
    readonly string CorsPolicy = "_corsPolicy ";

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: CorsPolicy,
                              builder =>
                              {
                                  builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      .AllowCredentials();
                              });
        });

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers()
                     .RequireCors(CorsPolicy)
        });
    }
}

启用带有属性的CORS

你有两个选择

[EnableCors]默认策略。 [EnableCors("{Policy String}")]指定命名策略。

对于“c# - ASP Net Core Web API (Net Core 3.1 LTS)”,它为我工作…

在Startup.cs文件:

在“ConfigureServices”函数中添加以下代码:

services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy",
        builder => builder.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader());
});

注意:在“CorsPolicy”的情况下,你可以改变你喜欢的或在“Startup”类中使用全局变量。

在“Configure”函数中添加以下代码:

app.UseCors("CorsPolicy");

检查函数的调用顺序,它应该是这样的:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});          

最后,在你的控制器类中,将下面的代码添加到你的函数之上:

[EnableCors("CorsPolicy")]

例如:

[EnableCors("CorsPolicy")]
[HttpPost("UserLoginWithGoogle")]
public async Task<ActionResult<Result>> UserLoginWithGoogle([FromBody] TokenUser tokenUser)
{            
    Result result = await usersGoogleHW.UserLoginWithGoogle(tokenUser.Token);
    return new JsonResult(result);
}

注意:“CorsPolicy”必须在启动和控制器中匹配。

祝你好运……

ASP。NET Core 6:

var  MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      builder =>
                      {
                          builder.WithOrigins("http://example.com",
                                              "http://www.contoso.com");
                      });
});

// services.AddResponseCaching();

builder.Services.AddControllers();

var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthorization();

app.MapControllers();

app.Run();

更多样品请参考官方文档。


ASP。NET Core 3.1和5.0:

你必须在应用程序启动时在ConfigureServices方法中配置CORS策略:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
    {
        builder.WithOrigins("http://example.com")
               .AllowAnyMethod()
               .AllowAnyHeader();
    }));

    // ...
}

builder中的CorsPolicyBuilder允许您根据需要配置策略。你现在可以使用这个名字将策略应用到控制器和动作上:

[EnableCors("MyPolicy")]

或者把它应用到每一个请求上:

public void Configure(IApplicationBuilder app)
{
    app.UseCors("MyPolicy");

    // ...

    // This should always be called last to ensure that
    // middleware is registered in the correct order.
    app.UseMvc();
}

特别是在dotnet核心2.2中,你必须改变SignalR

.WithOrigins (http://localhost: 3000)或

.SetIsOriginAllowed(isOriginAllowed: _ => true) //所有源

用.AllowCredentials()代替。allowanyorigin ()

https://trailheadtechnology.com/breaking-change-in-aspnetcore-2-2-for-signalr-and-cors/

https://github.com/aspnet/AspNetCore/issues/4483