。net内核允许在使用CORS时发回错误401(而不是零)

问题描述 投票:0回答:1

我的客户端JS应用实际上是401时收到状态代码0。当我使用邮递员运行相同的请求时,我得到了预期的401。

我启用了以下功能:

services.AddCors(o => o.AddPolicy("cors", builder =>
            {
                builder.WithOrigins("http://localhost:4200")
                       .AllowAnyMethod()
                       .AllowAnyHeader()
                       .AllowCredentials();
            }));

....
app.UseCors("cors");

在没有身份验证问题时,cors仍在工作(401)。

我应该是401时在客户端收到错误代码0。

enter image description here

api asp.net-core cors http-status-codes
1个回答
0
投票

此错误的原因很可能是服务器和Web浏览器上的CORS的组合。

原因:我的猜测是,服务器响应中缺少某些必需的CORS标头。使用不正确的Cors标头时,浏览器返回0状态。

解决方案:再次,我会猜测您正在注册中间件的顺序不正确。根据文档:

使用端点路由,必须将CORS中间件配置为在对UseRouting和UseEndpoints的调用之间执行。不正确的配置将导致中间件停止正常运行。

我会以这样的顺序向您注册中间件:

app.UseRouting();
app.UseCors("cors");
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});
© www.soinside.com 2019 - 2024. All rights reserved.