在Startup文件的ConfigureServices函數裏注入服務跨域
public void ConfigureServices(IServiceCollection services) { #region Cors跨域請求 services.AddCors(c => { c.AddPolicy("AllRequests", policy => { policy .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); #endregion services.AddControllers(); }
在其後的Configure函數中開啓中間件app
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); //開啓Cors跨域請求中間件 app.UseCors("AllRequests"); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }