标签:ade app ons 配置 dev rmi swa ati 文件
初次用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();
} }
标签:ade app ons 配置 dev rmi swa ati 文件
原文地址:https://www.cnblogs.com/li150dan/p/12762681.html