Javascript 请求始终被CORS策略c net core阻止
嗨,我遇到了cors错误的问题,我阅读了stack和其他网站的所有示例,但任何示例都帮不了我。 我用NetCore2.1编写了RESTAPI,使用react framework的客户端应用程序,我尝试从RESTAPI获取api,所有这些都在本地主机上。 服务器打开,客户端响应打开 当我尝试在服务器上获取api时,出现以下异常: Microsoft.AspNetCore.Cors.Infrastructure.CorsService:信息:策略执行失败。 Microsoft.AspNetCore.Cors.Infrastructure.CorsService:信息:Cors策略中不允许请求标头“访问控制允许来源”。 Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求在3.9493ms 204中完成 但在react客户端的浏览器上,我得到以下信息: CORS策略已阻止从源站获取的访问:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许源站”标头。如果不透明响应满足您的需要,请将请求的模式设置为“no cors”,以获取禁用cors的资源 这是我的c类,当我注册cors时,我记得在.AddMvc方法后面注册实例Javascript 请求始终被CORS策略c net core阻止,javascript,c#,.net-core,Javascript,C#,.net Core,嗨,我遇到了cors错误的问题,我阅读了stack和其他网站的所有示例,但任何示例都帮不了我。 我用NetCore2.1编写了RESTAPI,使用react framework的客户端应用程序,我尝试从RESTAPI获取api,所有这些都在本地主机上。 服务器打开,客户端响应打开 当我尝试在服务器上获取api时,出现以下异常: Microsoft.AspNetCore.Cors.Infrastructure.CorsService:信息:策略执行失败。 Microsoft.AspNetCore.
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);
}
我将react代码粘贴到获取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);
}
在Configure services方法中添加以下代码
services.AddCors(options =>
{
// this defines a CORS policy called "default"
options.AddPolicy("default", policy =>
{
policy.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
在配置方法内
app.UseCors("default");
在Configure services方法中添加以下代码
services.AddCors(options =>
{
// this defines a CORS policy called "default"
options.AddPolicy("default", policy =>
{
policy.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
在配置方法内
app.UseCors("default");