初次用net core 3.1 開發webapi接口時遇到跨域問題,花費了點時間從網上找的資料,但是有些不全,所以下面就粘貼上解決辦法,已經測試過,沒問題的。
修改項目中的Startup類,添加紅色字體標注的代碼,注意這是ASP.NET Core 3.1 跨域解決辦法
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.AddCors(options => { options.AddPolicy("cors", builder => builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod() ); }); services.AddControllers(); services.AddMvcService(); //注冊Swagger生成器 services.AddSwaggerService();
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } applicationLifetime.ApplicationStarted.Register(() => { //網站啟動完成執行 }); applicationLifetime.ApplicationStopping.Register(() => { //網站停止過程中執行 }); applicationLifetime.ApplicationStopped.Register(() => { //網站停止完成執行 }); app.UseRouting(); //允許所有跨域,cors是在ConfigureServices方法中配置的跨域策略名稱 //注意:UseCors必須放在UseRouting和UseEndpoints之間 app.UseCors("cors"); //使用靜態文件 app.UseStaticFiles(); app.UseAuthorization(); app.UseEndpoints(endpoints => { //跨域需添加RequireCors方法,cors是在ConfigureServices方法中配置的跨域策略名稱 endpoints.MapControllers().RequireCors("cors"); }); //調用中間件 app.UseSwaggerMiddleware();
} }