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

.NET Core 6 WebAPI对接React时CORS错误排查求助

.NET Core 6 Web服务CORS错误问题

我有一个基于.NET Core 6编写的简易Web服务,被React应用调用时每次请求都返回CORS错误:

Access to XMLHttpRequest at 'https://localhost:7023/api/auth/login' from origin 'https://azmeits1:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

以下是Web服务Program.cs中的初始代码:

builder.Services.AddDbContext<WpmDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});

builder.Services.AddCors(); 

var app = builder.Build();

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

//app.UseRouting();
app.UseHttpsRedirection();

app.UseCors(x => x
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader());

app.UseAuthentication();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});
app.Run();

我知道中间件顺序很重要,但无论怎么调整,部署环境里始终出现相同的CORS错误。

我还尝试了另一种CORS配置:

var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins, policy =>
    {
        policy
        .SetIsOriginAllowed(origin => true)
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials();
    });
});

var app = builder.Build();

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

//app.UseRouting();
app.UseHttpsRedirection();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthentication();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});
app.Run();

不确定控制器代码是否有影响,附上控制器代码:

namespace TestAPI.Controllers
{
    [Route("api/auth")]
    [ApiController]
    [Authorize]
    public class AuthController : ControllerBase
    {
        [HttpPost("login")]
        [AllowAnonymous]
        public ActionResult<string> Login([FromBody] UserDto request)
        {
            //login code
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 18:32:21