[英]Request always has been blocked by CORS policy c# net core
Hi i have trouble with cors error i read the all examples from stack and other website but any dont helped me. 嗨,我遇到了cors错误的麻烦,我从堆栈和其他网站上阅读了所有示例,但没有任何帮助。 I have the rest api written in net core 2.1 and the client app( i use react framework) and i try to fetch api from rest api, all was on the localhost. 我有用Net Core 2.1和客户端应用程序编写的其余api(我使用react框架),我尝试从其余api获取api,所有这些都在本地主机上。 Server on http://localhost:44334 and react client on http://localhost:3000 When i try to fetch api on the server i get this exception: http:// localhost:44334上的服务器,并在http:// localhost:3000上反应客户端,当我尝试在服务器上获取api时,出现此异常:
Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: Policy execution failed. Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information:策略执行失败。 Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: Request header 'access-control-allow-origin' not allowed in CORS policy. Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information:CORS策略中不允许请求标头“ access-control-allow-origin”。 Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 3.9493ms 204 Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求在3.9493ms中完成204
But on the react client on browser i get this: 但是在浏览器上的react客户端上我得到了这个:
Access to fetch at ' https://localhost:44334/Account ' from origin ' http://localhost:3000 ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 从起源' http:// localhost:3000 '到' https:// localhost:44334 / Account '处获取的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否'访问控制-Allow-Origin'标头出现在请求的资源上。 If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 如果不透明的响应满足您的需求,请将请求的模式设置为“ no-cors”,以在禁用CORS的情况下获取资源。
This is my c# class when i register cors, i remember to register instance behind .AddMvc method 这是我注册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);
}
And register on Configure method: 并在Configure方法上注册:
app.UseCors(
options => options.WithOrigins("http://localhost:3000").AllowAnyMethod()
);
app.UseMvc();
And this i paste the react code where i fetch api: 然后我将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));
} }
And the controller method on this i dont use EnableCors: 在此控制器方法我不使用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);
}
Add below code Within Configure services method 在配置服务方法中添加以下代码
services.AddCors(options =>
{
// this defines a CORS policy called "default"
options.AddPolicy("default", policy =>
{
policy.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Within configure method 在配置方法内
app.UseCors("default");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.