我已经通读了类似的问题,尝试了其中提到的几个解决方案,但都没有成功-问题很简单,我真的不知道到底会错在哪里。。。
我有一个非常简单的.NET核心API,我想在上面设置CORS。
我尝试过这种方式(端点路由(:https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0#启用cors与端点路由
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://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0#启用具有属性的cors
以这种方式启动
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控制台中收到一个错误,比如:访问XMLHttpRequesthttp://localhost:4000/simplexsolver/solve'来自原点'http://localhost:4200'已被CORS策略阻止:请求的资源上不存在"Access Control Allow Origin"标头
我完全按照文章所说的去做,但没有任何结果。。。我感谢任何帮助!
更新
我终于成功启用了CORS。可悲的是,我无法在ConfigureServices中设置任何类型的策略,因为如果我这样做,Access Control Allow Origin标头将具有"*"飞行前请求响应中的值(而不是前端的地址(。我使用的方式是:
- 在ConfigureServices((方法中,只添加CORS而不添加任何策略
- 在Configure((中,我将余量确定为UseCors((方法的参数(不需要以这种方式将EnableCors属性放在控制器的mnethod上。(
现在我在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有什么问题。
将您的代码修复为:
app.UseCors("Policy1");
services.AddCors(options =>
{
options.AddPolicy("Policy1",
builder =>
{
.builder.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
并删除
[EnableCors("Policy1")]
来自控制器动作。
我能够像这样在.NET Core 3.1:中全局允许CORS
Startup.cs代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy(name: "AllowCORS", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("AllowCORS");
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
使用此:
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);
//...
}
我需要更改调用应用程序的顺序。在配置中使用CORS("CORS_POLICY"(。
无效:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.ConfigureMetrics();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseUserContextClaimsInjector();
app.UseGlobalExceptionHandlerMiddleware();
app.UseResponseCompression();
app.UseSwagger();
app.UseSwaggerUI();
app.UseStaticFiles();
app.ConfigureHealthCheck();
app.UseResponseCompression();
app.UseCors("CORS_POLICY");
作品:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("CORS_POLICY");
app.ConfigureMetrics();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseUserContextClaimsInjector();
app.UseGlobalExceptionHandlerMiddleware();
app.UseResponseCompression();
app.UseSwagger();
app.UseSwaggerUI();
app.UseStaticFiles();
app.ConfigureHealthCheck();