问题描述
我正在尝试在ASP.NET Core Web API上启用跨源资源共享,但是我遇到了麻烦.
I am trying to enable cross origin resources sharing on my ASP.NET Core Web API, but I am stuck.
EnableCors
属性接受类型为string
的policyName
作为参数:
The EnableCors
attribute accepts policyName
of type string
as parameter:
// 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.NET Core Web API上配置 CORS ?
What does the policyName
mean and how can I configure CORS on an ASP.NET Core Web API?
推荐答案
您必须在应用程序启动时使用ConfigureServices
方法配置CORS策略:
You have to configure a CORS policy at application startup in the ConfigureServices
method:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
// ...
}
builder
中的CorsPolicyBuilder
允许您根据需要配置策略.现在,您可以使用该名称将策略应用于控制器和操作:
The CorsPolicyBuilder
in builder
allows you to configure the policy to your needs. You can now use this name to apply the policy to controllers and actions:
[EnableCors("MyPolicy")]
或将其应用于每个请求:
Or apply it to every request:
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();
}
这篇关于如何在ASP.NET Core中启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!