我正在尝试在我的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?
特别是在dotnet核心2.2中,你必须改变SignalR
.WithOrigins (http://localhost: 3000)或
.SetIsOriginAllowed(isOriginAllowed: _ => true) //所有源
用.AllowCredentials()代替。allowanyorigin ()
https://trailheadtechnology.com/breaking-change-in-aspnetcore-2-2-for-signalr-and-cors/
https://github.com/aspnet/AspNetCore/issues/4483
对于“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”类中使用全局变量。
在“Configure”函数中添加以下代码:
app.UseCors("CorsPolicy");
检查函数的调用顺序,它应该是这样的:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
最后,在你的控制器类中,将下面的代码添加到你的函数之上:
[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”必须在启动和控制器中匹配。
祝你好运……
得到这个工作与。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