ASP.NET Core 3.1 跨域问题解决方式
初次用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();
} }
分类:
.NET Core
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现