.net 核心允许在使用 CORS 时发回错误 401(而不是零) [英] .net core allowing sending back error 401 when using CORS (instead of zero)

查看:35
本文介绍了.net 核心允许在使用 CORS 时发回错误 401(而不是零)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My client JS app is receiving status code 0 when it is actually 401.
When I use postman for running the same request i am getting 401 as expected.

我已启用 cors 如下:

I have enabled cors as the following:

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

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

cors 在没有身份验证问题 (401) 时正常工作.

The cors is working when there is no authentication problem (401).

我在客户端收到错误代码 0,而它应该是 401.

I am getting error code 0 in the client-side when it is supposed to be 401.

推荐答案

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

The cause of this error is a most likely a combination of CORS on your server and the web browser.

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

Cause: My guess is, some of the required CORS headers are missing from your server response. Browsers return a status of 0 when incorrect Cors headers are used.

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

Solution: Again I will guess the order you are registering your middleware is incorrect. As per the docs:

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

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.

我会按照这样的顺序为您注册中间件(取决于您使用的中间件):

I would register you middleware in an order like so (depending on what middlewares you're using):

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

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});
...
//register app.UseMvc(); last

这篇关于.net 核心允许在使用 CORS 时发回错误 401(而不是零)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆