c# - CORS 不适用于 .NET Core API 和 Angular 前端
问题描述
我已经阅读了类似的问题,尝试了其中提到的几个解决方案,但没有任何成功 - 问题很简单,我真的不知道到底有什么错误......
我有一个非常简单的 .NET Core API,我想在其上设置 CORS。
我试过这种方式(端点路由):https ://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0#enable-cors-with-endpoint-routing
Startup.cs 中的 ConfigureServices() 和 Configure() 方法
完全是默认生成的,只是添加了 MSDN 的 CORS 相关代码。
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: "Policy1",
builder =>
{
// I read the site url from appsettings.json but for now I want to keep the example as simple as I can
// var lpSolverFrontendUrl = Configuration.GetValue<string>("Cors:AllowedSite");
builder.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod();
});
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors("Policy1");
});
}
我的控制器类
[Route("[controller]/[action]")]
public class SimplexSolverController : Controller
{
public IActionResult Ping()
{
return Json(new { status = "OK" });
}
[HttpPost]
public IActionResult Solve([FromBody] LPModelDto lpModelDto)
{
bool wrongFormat = false;
string message = null;
SimplexSolutionDto solution = null;
//...
}
//...
}
我已经尝试过的另一种方式(带有属性):https ://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0#enable-cors-with-attributes
Startup.cs 这样
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: "Policy1",
builder =>
{
// I read the site url from appsettings.json but I want to keep the example as simple as I can
// var lpSolverFrontendUrl = Configuration.GetValue<string>("Cors:AllowedSite");
builder.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod();
});
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
我的控制器类这样
我将EnableCors属性放在控制器方法上以启用 CORS。
[Route("[controller]/[action]")]
public class SimplexSolverController : Controller
{
public IActionResult Ping()
{
return Json(new { status = "OK" });
}
[EnableCors("Policy1")]
[HttpPost]
public IActionResult Solve([FromBody] LPModelDto lpModelDto)
{
bool wrongFormat = false;
string message = null;
SimplexSolutionDto solution = null;
//...
}
//...
}
无论我选择哪种方式,我都会在 DevTools 控制台中收到错误,例如:CORS 策略已阻止从源“http://localhost:4200”访问“http://localhost:4000/simplexsolver/solve”处的 XMLHttpRequest :请求的资源上不存在“Access-Control-Allow-Origin”标头。
我完全按照文章所说的但没有任何结果......我感谢任何帮助!
更新
我终于成功启用了CORS。可悲的是,我无法在 ConfigureServices 中设置任何类型的策略,因为如果我这样做,Access-Control-Allow-Origin 标头将在预检中具有“*”值(不是前端的地址)请求的响应。我使用的方式是:
- 在 ConfigureServices() 方法中只添加 CORS 而不添加任何策略
- 在 Configure() 中,我将余量确定为 UseCors() 方法的参数(无需以这种方式将 EnableCors 属性放在控制器方法上。)
现在我在 Startup.cs 中的两个方法如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(options => options.WithOrigins(Configuration.GetValue<string>("Cors:AllowedSite")).AllowAnyMethod().AllowAnyHeader().AllowCredentials());
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
谢谢你给我的所有答案!我希望这对将来的某人有所帮助。但对我来说,将 CORS 与策略一起使用有什么问题仍然让我感到奇怪。
解决方案
用这个:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowOrigin", builder =>
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
//...
}
如果它不起作用,请将 Mvc 兼容版本设置为 3.0 使用
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
像这样:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowOrigin", builder =>
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
//...
}
推荐阅读
- go - 当服务器使用 gin-gonic 和 gin-contrib/gzip 发生恐慌时,HTTP 客户端收到状态码 200
- python - 我可以制作和运行的最简单的软件包是什么?
- javascript - 将(JSON、JS)数据加载到 Mapbox
- angular - 你如何告诉组件使用特定的模板文件?
- r - R:在for循环中命名矩阵行/列在控制台中有效,但在编织时无效
- excel - 随机分布到一个矩阵
- python - 如何在 Matplotlib 中注册倒数(1/x)比例?
- google-sheets - 为几个不同的行(数组)创建单个公式(谷歌表格)
- ios - 对如何/在哪里设置 Xib 的高度感到困惑
- matlab - 调用期间未分配输出参数:Matlab