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

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

问题描述

我的客户端JS应用实际上是401时正在接收状态代码0.
当我使用邮递员运行相同的请求时,我得到了预期的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天全站免登陆