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