.net 核心允许在使用 CORS(而不是零)时发回错误 401
.net core allowing sending back error 401 when using CORS (instead of zero)
我的客户端 JS 应用收到状态码 0,但实际上是 401。
当我将邮递员用于 运行 相同的请求时,我得到了预期的 401。
我启用了以下cors:
services.AddCors(o => o.AddPolicy("cors", builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));
....
app.UseCors("cors");
没有验证问题 (401) 时,cors 正在运行。
当它应该是 401 时,我在客户端收到错误代码 0。
此错误的原因很可能是您的服务器和 Web 浏览器上的 CORS 组合。
原因: 我的猜测是,您的服务器响应中缺少一些必需的 CORS headers。浏览器 return 使用不正确的 Cors headers 时状态为 0。
解决方案: 我再次猜测您注册中间件的顺序不正确。
根据文档:
With endpoint routing, the CORS middleware must be configured to
execute between the calls to UseRouting and UseEndpoints. Incorrect
configuration will cause the middleware to stop functioning correctly.
我会按照这样的顺序注册你的中间件(取决于你使用的是什么中间件):
app.UseRouting();
app.UseCors("cors");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
...
//register app.UseMvc(); last
我的客户端 JS 应用收到状态码 0,但实际上是 401。
当我将邮递员用于 运行 相同的请求时,我得到了预期的 401。
我启用了以下cors:
services.AddCors(o => o.AddPolicy("cors", builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));
....
app.UseCors("cors");
没有验证问题 (401) 时,cors 正在运行。
当它应该是 401 时,我在客户端收到错误代码 0。
此错误的原因很可能是您的服务器和 Web 浏览器上的 CORS 组合。
原因: 我的猜测是,您的服务器响应中缺少一些必需的 CORS headers。浏览器 return 使用不正确的 Cors headers 时状态为 0。
解决方案: 我再次猜测您注册中间件的顺序不正确。 根据文档:
With endpoint routing, the CORS middleware must be configured to execute between the calls to UseRouting and UseEndpoints. Incorrect configuration will cause the middleware to stop functioning correctly.
我会按照这样的顺序注册你的中间件(取决于你使用的是什么中间件):
app.UseRouting();
app.UseCors("cors");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
...
//register app.UseMvc(); last