ReactJS调用ASP.Net Core 2.1接口出现CORS跨域错误如何解决?
我在React JS中使用axios发起POST请求调用ASP.NET Core端接口时,出现如下CORS跨域错误:
Failed to load resource: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. https://localhost:5001/api/vendorregistration
已安装以下Nuget包,参照网上配置方案操作后问题仍未解决:
- Microsoft.AspNet.Cors 5.2.7版本
- Microsoft.AspNetCore.Cors 2.1.1版本
现有配置代码
Startup.cs 配置
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddCors(o => o.AddPolicy("ReactPolicy", builder => { builder.AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin(); // .AllowCredentials(); })); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseStaticFiles(); app.UseCookiePolicy(); app.UseHttpsRedirection(); app.UseCors("ReactPolicy"); app.UseMvc(); } }
VendorRegistrationController.cs 代码
namespace Bait.Controllers { [Produces("application/json")] [Route("api/[controller]")] [ApiController] [EnableCors("ReactPolicy")]
React端 RegistrationForm.tsx 请求代码
const handleFormSubmit = async (values: any): Promise<any> => { const response = await axios.post<User>('https://localhost:5001/api/vendorregistration', { data: values }) console.log(response); };
卸载冗余Nuget包
Microsoft.AspNet.Cors是传统ASP.NET非Core框架的CORS依赖包,和你使用的ASP.NET Core 2.1完全不兼容,直接卸载该包,仅保留Microsoft.AspNetCore.Cors即可。调整中间件注册顺序
ASP.NET Core的中间件按注册顺序执行,你当前将CORS中间件放在HTTPS重定向中间件之后,请求重定向时的响应不会携带CORS头,直接触发跨域错误。将app.UseCors("ReactPolicy")移到app.UseHttpsRedirection()之前,修改后的Configure方法如下:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } // CORS中间件放在所有处理请求的中间件最前面 app.UseCors("ReactPolicy"); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseHttpsRedirection(); app.UseMvc(); }
确认本地HTTPS证书信任
你请求的是HTTPS协议接口,先在浏览器直接访问https://localhost:5001,确认没有证书不安全提示,如果有提示需要将ASP.NET Core本地开发证书加入系统信任列表。凭证场景适配(可选)
如果后续请求需要携带Cookie、Authorization等凭证信息,CORS规范不允许AllowAnyOrigin和AllowCredentials同时使用,需要修改CORS策略配置如下:
services.AddCors(o => o.AddPolicy("ReactPolicy", builder => { builder.AllowAnyHeader() .AllowAnyMethod() .WithOrigins("http://localhost:3000") // 明确指定前端地址 .AllowCredentials(); }));
内容的提问来源于stack exchange,提问作者Yavuz

