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


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();
}

根据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")]

适用于。net Core 1和。net Core 2

如果使用.Net-Core 1.1

不幸的是,在这个特定的情况下,文件非常混乱。所以我要让它变得非常简单:

将Microsoft.AspNetCore.Cors nuget包添加到项目中 在ConfigureServices方法中添加services.AddCors(); 在Configure方法中,在调用app.UseMvc()和app.UseStaticFiles()之前,添加: app.UseCors(生成器=>生成器 .AllowAnyOrigin () .AllowAnyMethod () .AllowAnyHeader () .AllowCredentials ());

就是这样。每个客户端都可以访问您的ASP。NET核心网站/API。


如果使用。net - core 2.0

Add Microsoft.AspNetCore.Cors nuget package to your project in ConfigureServices method, before calling services.AddMvc(), add: services.AddCors(options => { options.AddPolicy("AllowAll", builder => { builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); }); }); (Important) In Configure method, before calling app.UseMvc(), add app.UseCors("AllowAll"); "AllowAll" is the policy name which we need to mention in app.UseCors. It could be any name.

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"));
    });            
}

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

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

如果你在IIS上托管,一个可能的原因是你得到这个是因为IIS阻塞选项动词。我为此花了将近一个小时:

一个明显的迹象是在OPTIONS请求期间出现404错误。

要解决这个问题,您需要显式地告诉IIS不要阻止OPTIONS请求。

进入请求过滤:

确保允许使用OPTIONS:

或者,只是做一张网。配置如下设置:

<system.webServer>
    <security>
        <requestFiltering>
            <verbs>
                <remove verb="OPTIONS" />
                <add verb="OPTIONS" allowed="true" />
            </verbs>
        </requestFiltering>
    </security>
</system.webServer>

特别是在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

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

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

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

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

步骤1:我们需要微软. aspnetcore . cors包在我们的项目。安装请进入“Tools -> NuGet Package Manager -> Manage NuGet Packages For Solution”。搜索“Microsoft.AspNetCore.Cors”,安装软件包。

步骤2:我们需要将CORS注入到容器中,以便应用程序可以使用它。在Startup.cs类中,让我们转到ConfigureServices方法并注册CORS。

因此,在我们的服务器应用程序中,让我们进入Controllers -> homeconcontroller .cs,并将EnableCors装饰器添加到Index方法(或您特定的控制器和动作):

更多详情请点击这里

得到这个工作与。net Core 3.1如下

确保你把UseCors代码放在app.UseRouting()之间;和app.UseAuthentication ();

app.UseHttpsRedirection();

app.UseRouting();
app.UseCors("CorsApi");

app.UseAuthentication();
app.UseAuthorization();

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

然后将此代码放在ConfigureServices方法中

services.AddCors(options =>
{
    options.AddPolicy("CorsApi",
        builder => builder.WithOrigins("http://localhost:4200", "http://mywebsite.com")
            .AllowAnyHeader()
            .AllowAnyMethod());
});

在基本控制器上面我放了这个

[EnableCors("CorsApi")]
[Route("api/[controller]")]
[ApiController]
public class BaseController : ControllerBase

现在我所有的控制器都将继承BaseController,并启用CORS

如果你得到错误“没有'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}")]指定命名策略。

在我设法在最琐碎的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.)

这涵盖每个端点。如果你想阻止某个端点,使用这个注释[DisableCors] 这里描述得很好。 https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0

在app.authentication()和app.routing()之间添加app.usecors(policyName)在Configure方法中。 在configureService方法中

services.AddCors(options => options.AddPolicy(name: mypolicy,     builder =>     { builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin(); }));

在每个控制器中添加[EnableCors("mypolicy")]

        [EnableCors("mypolicy")] 
        [Route("api/[controller]")] [ApiController] 
        public class MyController : ControllerBase


eg:-

  namespace CompanyApi2
        {
            public class Startup
            {
                public Startup(IConfiguration configuration)
                {
                    Configuration = configuration;
                }
        
                public IConfiguration Configuration { get; }
        
                // This method gets called by the runtime. Use this //method to add services to the container.
                public void ConfigureServices(IServiceCollection services)
                {
                    services.AddCors(options =>
                        options.AddPolicy(name: mypolicy,
                            builder =>
                            {
                                builder.AllowAnyHeader().AllowAnyMethod()
                                    .AllowAnyOrigin();
                            })); //add this
                    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
                    services.AddScoped<IDatarepository, DatabaseRepository>();
                }
        
                public string mypolicy = "mypolicy";
        
                // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
                public void Configure(IApplicationBuilder app, IHostingEnvironment env)
                {
                    if (env.IsDevelopment())
                    {
                        app.UseDeveloperExceptionPage();
                    }
                    else
                    {
                        app.UseHsts();
                    }
        
                    app.UseCors(mypolicy); //add this
                    app.UseHttpsRedirection();
                    app.UseMvc();
                }
            }
        }

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

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

得到这个工作与。net Core 3.1如下:

在ConfigureServices()方法中:

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

在Configure()方法中:

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
   ...
   app.UseCors(builder =>
          builder.AllowAnyOrigin()
          .AllowAnyHeader()
          .AllowAnyMethod()
        );
   ...
  }

安装nuget包Microsoft.AspNetCore.CORS

在ConfigureServices方法下的Startup.cs中,在services之前添加以下代码。

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

在Startup.cs的Configure方法中添加app.UseCors("AllowMyOrigin");调用app.UseMvc()之前

注意,当从客户端发送请求时,记得使用https而不是http。

.Net CORE 3.1使用:

app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())

注意“/”在最后-会阻塞CORS的原点

builder.WithOrigins("http://example.com/","http://localhost:55233/");

将阻止

use

builder.WithOrigins("http://example.com","http://localhost:55233"); 

ASP。NET核心Web API

在ConfigureServices中添加services.AddCors();之前services.AddControllers ();

在“配置”中添加UseCors

app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());

对于“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”必须在启动和控制器中匹配。

祝你好运……

对于Web API(ASP。Net core 6.0) 在Program.cs中,只需在builder.Build()之前添加;

builder.Services.AddCors(p => p.AddPolicy("corsapp", builder =>
{
    builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
}));

也添加

app.UseCors("corsapp");