我正在尝试在我的 ASP.NET Core Web API 上启用跨源资源共享,但我被卡住了。
EnableCors
属性接受 string
类型的 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.NET Core Web API 上配置 CORS?
对于 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();
有关更多示例,请参阅 official docs。
对于 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 1 和 .Net Core 2
如果使用 .Net-Core 1.1
不幸的是,在这种特定情况下,文档非常混乱。所以我会让它变得非常简单:
将 Microsoft.AspNetCore.Cors nuget 包添加到您的项目中
在 ConfigureServices 方法中,添加 services.AddCors();
在 Configure 方法中,在调用 app.UseMvc() 和 app.UseStaticFiles() 之前,添加: app.UseCors(builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials());
而已。每个客户端都可以访问您的 ASP.NET Core 网站/API。
如果使用 .Net-Core 2.0
将 Microsoft.AspNetCore.Cors nuget 包添加到您的项目中
在 ConfigureServices 方法中,在调用 services.AddMvc() 之前,添加: services.AddCors(options => { options.AddPolicy("AllowAll", builder => { builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials( ); }); });
(重要)在 Configure 方法中,在调用 app.UseMvc() 之前,添加 app.UseCors("AllowAll"); “AllowAll”是我们需要在 app.UseCors 中提及的策略名称。它可以是任何名称。
.UseMvc()
之前的 .UseCors()
基于 Henk's answer,我已经能够提出特定域、我想要允许的方法以及我想要启用 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")]
To critique or request clarification from an author
我认为这里不是这种情况,Henk 的答案已经被标记。如果您想允许特定域,我的回答是附加组件。
ConfigureCors
已更改为 AddCors
。
如下所示与.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
place the UseCors code between app.UseRouting(); and app.UseAuthentication();
之前,事情对我没有用
[EnableCors]
和 .Net 5 中进行了测试。
如果您在 IIS 上托管,一个可能的原因是您得到这个是因为 IIS 阻止了 OPTIONS
动词。因为这个,我花了将近一个小时:
一个明显的迹象是您在 OPTIONS
请求期间收到 404
错误。
要解决此问题,您需要明确告诉 IIS 不 阻止 OPTIONS
请求。
转到请求过滤:
https://i.stack.imgur.com/K9Gu4.png
确保允许 OPTIONS:
https://i.stack.imgur.com/e20to.png
或者,只需使用以下设置创建一个 web.config
:
<system.webServer>
<security>
<requestFiltering>
<verbs>
<remove verb="OPTIONS" />
<add verb="OPTIONS" allowed="true" />
</verbs>
</requestFiltering>
</security>
</system.webServer>
特别是在带有 SignalR 的 dotnet core 2.2 中,您必须更改
.WithOrigins("http://localhost:3000")
或
.SetIsOriginAllowed(isOriginAllowed: _ => true) //for all origins
用 .AllowCredentials()
代替 .AllowAnyOrigin()
https://trailheadtechnology.com/breaking-change-in-aspnetcore-2-2-for-signalr-and-cors/
https://github.com/aspnet/AspNetCore/issues/4483
您必须在 Startup.cs 类中进行配置
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
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"));
});
}
您可以通过三种方式启用 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 时,必须在 UseResponseCaching 之前调用 UseCors。
使用默认策略启用 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}")] 指定命名策略。
[EnableCors]
属性,但我仍然收到 CORS 错误,这里肯定有其他问题
上面提到的所有解决方法可能有效,也可能无效,在大多数情况下都无效。我在这里给出了解决方案
Currently I am working on Angular and Web API(.net Core) and came across CORS issue explained below
上面提供的解决方案将始终有效。对于“OPTIONS”请求,确实有必要启用“匿名身份验证”。使用此处提到的解决方案,您不必执行上述所有步骤,例如 IIS 设置。
无论如何,有人将我上面的帖子标记为与这篇文章重复,但我可以看到这篇文章只是为了在 ASP.net Core 中启用 CORS,但我的帖子与在 ASP.net Core 和 Angular 中启用和实现 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>
第 1 步:我们的项目中需要 Microsoft.AspNetCore.Cors 包。要安装,请转到工具 -> NuGet 包管理器 -> 管理 NuGet 包以获取解决方案。搜索 Microsoft.AspNetCore.Cors 并安装包。
第 2 步:我们需要将 CORS 注入到容器中,以便应用程序可以使用它。在 Startup.cs 类中,我们进入 ConfigureServices 方法并注册 CORS。
https://i.stack.imgur.com/3AgCw.png
因此,在我们的服务器应用程序中,让我们转到 Controllers -> HomeController.cs 并将 EnableCors 装饰器添加到 Index 方法(或您的特定控制器和操作):
https://i.stack.imgur.com/0AjLG.png
更多详情Click Here
在我设法在最琐碎的 CORS 问题上浪费了两个小时之后,一些故障排除技巧:
如果您看到记录了 CORS 策略执行失败...不要假设您的 CORS 策略没有正确执行。事实上,CORS 中间件可以正常工作,并且您的策略正在正确执行。这个措辞不好的消息的唯一含义是请求的来源与任何允许的来源都不匹配(参见源代码),即请求被禁止。来源检查(从 ASP.NET Core 5.0 开始)以一种非常简单的方式发生......即,您通过 WithOrigins() 提供的字符串与 HttpContext.Request.Headers 中存在的字符串之间进行区分大小写的序号字符串比较(参见源代码) [起源]。如果您使用尾部斜杠 / 设置允许的原点,或者它包含大写字母,CORS 可能会失败。 (就我而言,实际上我确实不小心复制了带有斜杠的主机。)
最近在 azure web app 上托管 web 应用服务器时,不得不编辑 azure app cors 设置来解决问题(仅代码没有解决问题)
安全性较低 - 启用 Access-Control-Allow-Credentials - 将其留空并添加 * 作为允许的来源 标记 Enable Access-Control-Allow-Credentials,然后添加您希望允许来自的请求的域
使用 .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()
);
...
}
对于 .Net CORE 3.1 使用:
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())
这涵盖了每个端点。如果您想阻止某些端点,请使用此注释 [DisableCors]
,它在此处进行了很好的描述。
https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0
在 app.authentication() 和 app.routing() 之间添加 app.usecors(policyName) 如果你在它上面使用 app.usMvc()。在 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
例如:-
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();
}
}
}
注意最后的“/” - 将阻止CORS起源
builder.WithOrigins("http://example.com/","http://localhost:55233/");
会阻止
利用
builder.WithOrigins("http://example.com","http://localhost:55233");
对于 ASP.NET Core Web API 5
在 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”类中的全局变量。
在“配置”函数中添加以下代码:
app.UseCors("CorsPolicy");
检查函数的调用顺序,它应该如下所示:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
最后在您的控制器类中,在您的函数 http 上方添加此代码:
[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");
安装 nuget 包 Microsoft.AspNetCore.CORS
在 ConfigureServices
方法下的 Startup.cs
中,在 services.AddMVC()
之前添加以下代码
services.AddCors(options =>
{
options.AddPolicy("AllowMyOrigin", p =>
{
p.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
在 Configure
方法内的 Startup.cs
中,在调用 app.UseMvc()
之前添加 app.UseCors("AllowMyOrigin");
请注意,从客户端发送请求时,请记住使用 https 而不是 http。
不定期副业成功案例分享
UseCors
扩展方法将 CORS 中间件添加到您的请求管道。请注意,CORS 中间件必须位于您的应用程序中您希望支持跨域的任何已定义端点之前请求(例如,在对UseMvc
的任何调用之前)。”