在Startup文件的ConfigureServices函数里注入服务
public void ConfigureServices(IServiceCollection services) { #region Cors跨域请求 services.AddCors(c => { c.AddPolicy("AllRequests", policy => { policy .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); #endregion services.AddControllers(); }
在其后的Configure函数中开启中间件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); //开启Cors跨域请求中间件 app.UseCors("AllRequests"); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }