简体   繁体   English

CORS 在 .NET 6.0 web api

[英]CORS in .NET 6.0 web api

I have a React app calling a .NET 6 Web API using Axios.我有一个使用 Axios 调用 .NET 6 Web API 的 React 应用程序。

In the program.cs file, I have added builder.Services.AddCors and app.UseCors as below.在 program.cs 文件中,我添加了 builder.Services.AddCors 和 app.UseCors,如下所示。

But I still get CORS error and 404 preflight.但我仍然收到 CORS 错误和 404 预检。

The method used to works in .NET 5 Web Api.该方法适用于 .NET 5 Web Api。

Is there anything we need to set for .NET 6 Web Api? .NET 6 Web Api 需要设置什么吗?

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
<removed>

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors();

// Add services to the container.
<removed>

// App settings
<removed>

<removed>

builder.Services.AddHttpContextAccessor();

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
    });

// AutoMapper
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

<removed>

// Firebase
<removed>

var app = builder.Build();

The CORS registration is CORS注册是

app.UseCors(x => x.AllowAnyHeader()
      .AllowAnyMethod()
      .WithOrigins("https://our-react-site.com"));

And the rest of the code和代码的rest

// Configure the HTTP request pipeline. 
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseSwagger();
app.UseSwaggerUI();

app.UseHttpsRedirection();

app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();

app.Run();

The CORS docs explain that UseCors middleware needs to be called in the correct order. CORS 文档解释说 UseCors 中间件需要以正确的顺序调用。

UseCors must be called in the correct order. UseCors 必须以正确的顺序调用。 For more information, see Middleware order .有关详细信息,请参阅中间件订单 For example, UseCors must be called before UseResponseCaching when using UseResponseCaching.例如,在使用 UseResponseCaching 时,必须在 UseResponseCaching 之前调用 UseCors。

The Middleware Order section shows that UseCors needs to be called after redirection and routing and before authentication and authorization. Middleware Order部分显示UseCors需要在重定向和路由之后以及身份验证和授权之前调用。

在此处输入图像描述

In your code you'll have to call UseCors after UseHttpsRedirection and right before UseAuthentication :在您的代码中,您必须在UseCors之后和UseHttpsRedirection之前UseAuthentication

app.UseHttpsRedirection();


app.UseCors(x => x.AllowAnyHeader()
      .AllowAnyMethod()
      .WithOrigins("https://our-react-site.com"));

app.UseAuthentication();

The documentation example shows this:文档示例显示了这一点:

var  MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      builder =>
                      {
                          builder.WithOrigins("http://example.com",
                                              "http://www.contoso.com");
                      });
});

// services.AddResponseCaching();

builder.Services.AddControllers();

var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthorization();

app.MapControllers();

app.Run();

Another difference is that the doc example creates at least one named policy and uses UseCors to apply this policy.另一个区别是文档示例创建了至少一个命名策略并使用UseCors来应用此策略。

added this to my program.cs file in .NET 6.0 web api将此添加到我的 program.cs 文件中 .NET 6.0 web api

app.UseCors(options => options.AllowAnyOrigin());

If you're using UseMiddleware , UseCors must be specified before it eg如果您使用的是UseMiddleware ,则必须在它之前指定UseCors例如

var app = builder.Build();

app.UseCors(policy => policy.AllowAnyHeader()
                            .AllowAnyMethod()
                            .SetIsOriginAllowed(origin => true)
                            .AllowCredentials());

app.UseMiddleware<ApiKeyMiddleware>();

You might be blocking the OPTIONS http verb in IIS. Check the "HTTP Verbs" Tab in Request Filtering settings in your IIS. Remove the highlighted option as shown in the image from the link below.您可能会阻止 IIS 中的选项 http 动词。检查 IIS 中请求过滤设置中的“HTTP 动词”选项卡。从下面的链接中删除突出显示的选项,如下图中所示。

IIS Request Filtering IIS 请求过滤

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM