我正在尝试在我的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?


当前回答

上面提到的所有解决办法都可能有效,也可能无效,在大多数情况下都行不通。我已经给出了答案

目前我正在研究Angular和Web API(.net Core),遇到了下面解释的CORS问题

上面提供的解决方案总是有效的。对于“OPTIONS”请求,真的有必要启用“匿名身份验证”。使用这里提到的解决方案,您不必执行上面提到的所有步骤,例如IIS设置。

不管怎样,有人把我上面的帖子标记为这篇帖子的副本,但我可以看到这篇帖子只是为了在ASP.net Core中启用CORS,但我的帖子与在ASP.net Core和Angular中启用和实现CORS有关。

其他回答

根据Henk的回答,我已经能够提出特定的域,我想允许的方法,以及我想启用CORS的头:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
         options.AddPolicy("AllowSpecific", p => p.WithOrigins("http://localhost:1233")
                                                   .WithMethods("GET")
                                                   .WithHeaders("name")));
    services.AddMvc();
}

用法:

[EnableCors("AllowSpecific")]

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

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

    services.Configure<MvcOptions>(options => {
        options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAnyOrigin"));
    });            
}

最近,当在azure web应用程序上托管web应用程序服务器时,不得不编辑azure应用程序cors设置来解决这个问题(只有代码没有解决这个问题)

不太安全-启用访问控制-允许-凭据-留空,并添加*作为允许的原点 标记为启用访问控制-允许凭据,然后添加希望允许来自的请求的域

在我设法在最琐碎的CORS问题上浪费了两个小时后,一些故障排除技巧:

If you see CORS policy execution failed logged... Don't assume that your CORS policy is not executing properly. In fact, the CORS middleware works, and your policy is executing properly. The only thing this badly worded message means is that the request's origin doesn't match any of the allowed origins (see source), i.e. the request is disallowed. The origin check (as of ASP.NET Core 5.0) happens in a very simple way... i.e. case-sensitive ordinal string comparison (see source) between the strings you provided via WithOrigins() and what exists in HttpContext.Request.Headers[Origin]. CORS can fail if you set an allowed origin with a trailing slash /, or if it contains uppercase letters. (In my case I did in fact accidentally copy the host with a trailing slash.)