我正在尝试在我的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();
}

其他回答

得到这个工作与。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

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

如果你在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>

这涵盖每个端点。如果你想阻止某个端点,使用这个注释[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();
                }
            }
        }

得到这个工作与。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()
        );
   ...
  }