javascript - 请求始终被 CORS 策略 c# net core 阻止
问题描述
嗨,我遇到了 cors 错误的问题,我从堆栈和其他网站上阅读了所有示例,但没有任何帮助我。我有用net core 2.1和客户端应用程序(我使用react框架)编写的rest api,我尝试从rest api获取api,一切都在本地主机上。http://localhost:44334上的服务器和http://localhost:3000上的客户端反应当 我尝试在服务器上获取 api 时,我得到了这个异常:
Microsoft.AspNetCore.Cors.Infrastructure.CorsService:信息:策略执行失败。Microsoft.AspNetCore.Cors.Infrastructure.CorsService:信息:CORS 策略中不允许请求标头“访问控制允许来源”。Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求在 3.9493 毫秒内完成 204
但是在浏览器上的反应客户端上,我得到了这个:
CORS 策略已阻止从源“http:// localhost:44334/Account ”获取从“ http ://localhost:3000 ”获取的访问权限:对预检请求的响应未通过访问控制检查:没有“访问控制” -Allow-Origin' 标头出现在请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
这是我注册 cors 时的 c# 类,我记得在 .AddMvc 方法后面注册实例
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
});
services.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddOptions();
services.AddMemoryCache();
var jwt_settings = Configuration.GetSettings<JwtSettings>();
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
cfg.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt_settings.Key)),
ValidIssuer = jwt_settings.Issuer,
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
ValidateLifetime = true
};
});
var builder = new ContainerBuilder();
//register commandModules
builder.Populate(services);
builder.RegisterModule(new ContainerModules(Configuration));
ApplicationContainer = builder.Build();
return new AutofacServiceProvider(ApplicationContainer);
}
并在 Configure 方法上注册:
app.UseCors(
options => options.WithOrigins("http://localhost:3000").AllowAnyMethod()
);
app.UseMvc();
我将反应代码粘贴到我获取 api 的位置:
export function login(password, email) {
fetch("https://localhost:44334/Account", {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
// "Content-Type": "application/x-www-form-urlencoded",
'Accept': 'application/json',
"Access-Control-Allow-Origin": "*"
},
body: {email, password}
}).then(res => res.json())
.then(response => console.log('Success:', response))
.catch(error => console.error('Error:', error));
}
我不使用EnableCors的控制器方法:
[HttpPost]
public async Task<IActionResult> Login([FromBody] LoginAsync login)
{
login.TokenId = Guid.NewGuid();
await _commandDispatcher.DispatchAsync(login);
var jwt = _memoryCache.Get<JsonWebToken>(login.TokenId);
return Json(jwt);
}
解决方案
在配置服务方法中添加以下代码
services.AddCors(options =>
{
// this defines a CORS policy called "default"
options.AddPolicy("default", policy =>
{
policy.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
在配置方法中
app.UseCors("default");
推荐阅读
- elasticsearch - 使用 Elasticsearch 查询按术语获取不同/唯一的文档
- angular - 使用Angular动态显示基于API值的图标
- flutter - 60 FPS 是什么意思在 Flutter 中如何一个屏幕每秒有 60 帧
- python - 如何将 CSV 转换为 Keyed JSON?
- python - 如何在 django 中获取与特定用户相关的 id
- syntax-error - 10170 用于打开/关闭 7 段 LED 的 Verilog 代码出现语法错误
- javascript - 如何修复 PHP 中的检查元素错误/错误?
- django - Django 无法使用 uWSGI 发送电子邮件
- python - 如何在 django 中检查 json 数据是否为空值
- javascript - 如何区分javascript中的变异函数和纯函数?