您好,我遇到了 cors 错误问题,我阅读了堆栈和其他网站上的所有示例,但没有任何帮助。 我有用 net core 2.1 编写的其余 api 和客户端应用程序(我使用 react 框架),我尝试从 rest api 获取 api,所有这些都在本地主机上。 服务器在 http://localhost:44334并在 http://localhost:3000 上对客户端使用react 当我尝试在服务器上获取 api 时出现此异常:
Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: Policy execution failed. Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: Request header 'access-control-allow-origin' not allowed in CORS policy. Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 3.9493ms 204
但是在浏览器的 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
这是我注册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();
然后我将 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 的 Controller 方法:
[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");
关于javascript - 请求总是被 CORS 策略阻止 c# net core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54579658/