且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

.NET Core UseCors()不添加标头

更新时间:2023-02-15 13:22:31

问题是,在使用Bearer身份验证(或我想象的任何一种)时,它会添加标头"Authorization",并且服务器只会给出该设置允许该标头.

The problem is that when using Bearer authentication (or any I would imagine), it adds a header "Authorization", and the server will only give an okay if the setup allows for that header.

有两种方法可以解决此问题,下面是仅 代码.它位于Web API解决方案的Startup.cs中的Configure()方法中.

There's two ways to solve the problem, and below is the only code needed. It goes in the Configure() method in Startup.cs in the Web API solution.

方法1::允许所有标头

app.UseCors(builder => builder.WithOrigins("https://localhost:44306")
                                .AllowAnyMethod()
                                .AllowAnyHeader());

方法2:允许特定的标题

app.UseCors(builder => builder.WithOrigins("https://localhost:44306")
                              .AllowAnyMethod()
                              .WithHeaders("authorization", "accept", "content-type", "origin"));

多余的标题是因为,根据文档:

The extra headers are because, per the documentation:

浏览器在设置Access-Control-Request-Headers的方式上并不完全一致.如果将标头设置为除"*"以外的其他任何内容,则应至少包括"accept","content-type"和"origin",以及要支持的所有自定义标头.

Browsers are not entirely consistent in how they set Access-Control-Request-Headers. If you set headers to anything other than "*", you should include at least "accept", "content-type", and "origin", plus any custom headers that you want to support.