You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 6 Web API配置特定源CORS后Ajax请求仍报错求助

问题:CORS配置完成但Ajax请求仍被拦截,SignalR连接正常

我查阅了多篇同类报错的帖子,尝试了各种配置组合和解决方案,均未解决问题。我已通过中间件+命名策略的方式启用CORS,配置逻辑参考官方文档规范。

JavaScript控制台报错:

Access to XMLHttpRequest at 'https://hotsauceodds.azurewebsites.net/api/glue/auth/ccb112d8-a2a8-4a1d-8786-b481889888f4' from origin 'https://monumental-fairy-0fe0e5.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

奇怪的是,SignalR连接完全正常,仅来自https://monumental-fairy-0fe0e5.netlify.app的Ajax请求失败。

我的配置代码如下:

using ArbWeb.TimerFeatures;
using DataAccess;
using Microsoft.AspNetCore.Mvc;
using Models.HubConfig;

var builder = WebApplication.CreateBuilder(args);

var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
        policy =>
        {
            policy.WithOrigins("http://localhost:4200", "https://monumental-fairy-0fe0e5.netlify.app")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
        });
});

builder.Services.AddControllersWithViews();
builder.Services.AddSignalR();
builder.Services.AddSingleton<TimerManager>();

builder.Services.Configure<ApiBehaviorOptions>(options => {
    options.InvalidModelStateResponseFactory = actionContext =>
    {
        ValidationProblemDetails error = actionContext.ModelState
            .Where(e => e.Value.Errors.Count > 0)
            .Select(e => new ValidationProblemDetails(actionContext.ModelState)).FirstOrDefault();

        return new BadRequestObjectResult(error);
    };
});

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthorization();

app.MapControllers();

app.MapHub<BroadcastHub>("/arb");

HotsauceOddsRepo.Initialize();

app.Run();

内容的提问来源于stack exchange,提问作者Evan Payne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 00:47:20