.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
相关产品推荐
相关产品推荐

