使用ASP.NET Core作为后端时,如何确保我的React获取请求不会收到CORS错误?[duplicate]

9gm1akwq  于 2023-01-22  发布在  .NET
关注(0)|答案(1)|浏览(223)
    • 此问题在此处已有答案**:

(37个答案)
3天前关闭。
我正在做一个使用React前端和ASP.NET后端的全栈项目(使用Visual Studio社区IDE)。我得到了CORS错误,我不知道如何修复。
我在React中调用了以下API:

const sendEmail = async(event) => {
        event.preventDefault();
        let baseUrl = '...some base url';
        let emailAddress = email.email_address;
        let emailMessage = emailText.message;
        let emailData = {
            "Id": "demo",
            "Amount": 37200,
            "Sig": "YTdjfyDBFNAKdufyBAiPPeefKLdjnf",
            "emailAddress": emailAddress,
            "notes": emailMessage
        };
        await fetch(`${baseUrl}/api/Email/Send`,{
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(emailData)
        })
        .then((res)=> res.json())
        .then((data) => console.log(data))
        .catch((err) => console.log(err));
    };

并且我从ASP.NET后端收到以下错误:
CORS策略已阻止从源"https://localhost:44493"在... "/api/Email/Send "中提取的访问权限:对印前检查请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头。如果不透明响应满足您的需要,请将请求的模式设置为"no-cors"以在禁用CORS的情况下提取资源。
这是我的Program.cs代码:

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddTransient<BillEmailService>();
builder.Services.AddTransient<TransactionInfoService>();
builder.Services.AddTransient<PaymentProviderService>();
builder.Services.AddTransient<StoreInfoService>();
builder.Services.AddTransient<DbSetup>();

builder.Services.AddTransient<InlineImageService>();
builder.Services.AddHttpClient<InlineImageService>();

builder.Services.AddTransient<Feedback>();

builder.Services.AddTransient<LoyaltyEngineFactory>();
builder.Services.AddHttpClient("LoyaltyEngineFactory");

builder.Services.AddTransient<MasterpassClientFactory>();
builder.Services.AddHttpClient("MasterpassClient");

builder.Services.AddTransient<TransactionInfoFactory>();
builder.Services.AddHttpClient("TransactionInfoClient");

builder.Services.AddSingleton<IDbConnectionFactory>(s => new DbConnectionFactory(connectionString));
builder.Services.AddTransient<IDbAdapter, DbAdapter>();

builder.Services.AddControllers().AddJsonOptions(options =>

    options.JsonSerializerOptions.PropertyNamingPolicy = null);

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApp", Version = "v1" });
});

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();

}

app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApp v1"));

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();
app.UseDefaultFiles();
app.UseStaticFiles();

app.MapControllerRoute("default", "{controller=Demo}/{action=Get}/{id?}");
app.MapFallbackToFile("index.html");


using var scope = app.Services.CreateScope();
var repo = scope.ServiceProvider.GetService<DbSetup>();
await repo!.RunScripts();

app.Run();

我该如何着手修复此错误?

u3r8eeie

u3r8eeie1#

如果出现CORS策略,您可以在inspect element =〉network...中看到,要处理此问题,您可以将响应URL或ip/port引入.NET核心应用程序

var  MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      policy  =>
                      {
                          policy.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();

请阅读更多:https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-7.0

相关问题