Asp.net CORS 已配置,但无法正常工作

时间:2021-04-14 08:27:14

标签: asp.net .net angular cors websecurity

我有一个用 API 编写的网络 asp.net core 5

CORS 的配置如下:

services.AddCors(options =>
        {
            string[] allowedOrigins = _config.GetValue<string>("AllowedOrigins")?.Split(",") ?? new string[0];
            options.AddPolicy("Default", builder =>
            {
                builder.AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials()
                .WithOrigins("http://localhost:4200");
            });
            options.AddPolicy("AllowAnyThing", builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyHeader()
                .AllowAnyMethod();
                // .AllowCredentials();
            });
            options.AddPolicy("Controlled", builder =>
           {
               builder.WithOrigins(allowedOrigins);
           });
        });

appsettings.json 包含以下部分:

"AllowedOrigins": "http://localhost:4200,https://localhost:4200",

客户是Angular 11.2

当我尝试通过客户端应用程序使用 api 时, 即使我删除并禁用 CORS 中的 API,它也会触发“CORS ERROR”。

我认为问题出在客户端,但我不知道如何解决。 感谢您的时间和关注。

1 个答案:

答案 0 :(得分:-1)

我尝试不使用 UseHttpsRedirection() 但它又发生了。我从浏览器中捕获的错误是:访问 XMLHttpRequest at 'localhost:5000/api/Controller/Action' from origin 'localhost:4200' has been Blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials'响应中的标头是“”,当请求的凭据模式为“包含”时,该标头必须为“真”。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。测试错误.component.ts


我添加了 localhost:4200 到允许的 origins 数组并且很高兴它工作了。

相关问题