我想将 CORS 从我的 Controller 启用到 asp.net core 2 应用程序,因此在 Controller 中我添加如下属性:
[EnableCors(origins: "*", headers: "accept,content-type,origin,x-my-header", methods: "*")]
但是我在起源上遇到错误:
The best overload for 'EnableCorsAttribute' does not have a parameter named 'origins'
因此,我从元数据访问 EnableCorsAttribute,并找到了以下方法:
namespace Microsoft.AspNetCore.Cors
{
public class EnableCorsAttribute : Attribute, IEnableCorsAttribute
{
public EnableCorsAttribute(string policyName);
public string PolicyName { get; set; }
}
}
但假设它是这样的方法:
public EnableCorsAttribute(string origins, string headers, string methods);
为什么我没有?我需要安装一些东西吗?我是 Asp.Net Core 的新手,我不明白为什么该方法不在我的 api 中。问候
最佳答案
Microsoft.AspNetCore.Cors
包中没有像 EnableCorsAttribute(string origins, string headers, string method)
这样的属性。
在您的场景中并基于 Enable Cross-Origin Requests (CORS) in ASP.NET Core :
如果提供的 cors 配置适用于整个应用程序,则在您的 ConfigureServices
方法中添加 cors 服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
然后在Configure
方法中使用全局cors中间件:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors(builder => builder
.WithOrigins("https://my.web.com", "http://localhost:5001")
.AllowAnyMethod()
.AllowCredentials()
.WithHeaders("Accept", "Content-Type", "Origin", "X-My-Header"));
//code omitted
}
将 ("https://my.web.com", "http://localhost:5001")
替换为您的来源。
如果您想拥有多个 cors 配置,则在 ConfigureServices
方法中:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("MyCorsPolicy", builder => builder
.WithOrigins("https://my.web.com", "http://localhost:5001")
.AllowAnyMethod()
.AllowCredentials()
.WithHeaders("Accept", "Content-Type", "Origin", "X-My-Header"));
});
}
在配置
方法中:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("MyCorsPolicy");
//code omitted
}
最后在 Controller 中:
[EnableCors("MyCorsPolicy")]
public class MyController : Controller
{ ... }
关于c# - EnableCorsAttribute 中缺少方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51068321/