【发布时间】:2021-12-20 01:55:07
【问题描述】:
我有一个使用 Axios 调用 .NET 6 Web API 的 React 应用程序。
在 program.cs 文件中,我添加了 builder.Services.AddCors 和 app.UseCors,如下所示。
但我仍然收到 CORS 错误和 404 预检。
用于在 .NET 5 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();
CORS 注册是
app.UseCors(x => x.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("https://our-react-site.com"));
还有剩下的代码
// 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();
【问题讨论】:
-
什么意思不工作?
-
当我们在 Chrome 中加载 React APP 时,我们得到:CORS 错误和 404 预检。
-
你打错了
UseCors电话 -
stackoverflow.com/questions/31942037/… 通过允许选项动词解决的问题。