
netcore 解决跨域问题(rush_peng)
3.在需要跨域的
发布日期:2021-05-04 20:59:00
浏览次数:35
分类:精选文章
本文共 1638 字,大约阅读时间需要 5 分钟。
1.在StartUp类的ConfigureServices方法中添加如下代码:
services.AddCors( //添加跨域 option => option.AddPolicy( "any", //跨域的名字 p => p .AllowAnyOrigin() // 允许任何域名 .AllowAnyHeader() // 允许任何head .AllowAnyMethod() // 允许任何方法 //.WithOrigins() // 允许哪些域名 ));
2.修改Configure方法
跨域声明应该放在路由的后面
// 允许所有跨域,cors是在ConfigureServices方法中配置的跨域策略名称 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); app.UseCors(); // 在中间使用跨域 app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
3.在需要跨域的Controller
上添加特性
[Route("api/Products/GetProducts")] [ApiController] public class BussinessController : ControllerBase { [EnableCors("any")] [HttpGet] public IActionResult GetProducts() { Listproducts = new List { new Product(){ id=1,price=5,productName="袜子"}, new Product() { id = 2, price = 49999, productName = "电脑" }, new Product() { id = 3, price = 120, productName = "鞋子" }, }; return Ok(products); } }
4.禁止跨域(在某个方法上禁止)
[HttpGet("{id}")][DisableCors]public string Get(int id){ return "value";}
参考:
【1】
【2】发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2025年04月07日 07时02分45秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
使用JWT作为Spring Security OAuth2的token存储
2021-05-09
使用Redis作为Spring Security OAuth2的token存储
2021-05-09
【SOLVED】Linux使用sudo到出现输入密码提示延迟时间长
2021-05-09
项目引入非配置的文件,打成war包后测试报错的可能原因
2021-05-09
Git学习笔记
2021-05-09
SpringBoot笔记
2021-05-09
让你的代码更优秀的 14 条建议
2021-05-09
不需要爬虫也能轻松获取 unsplash 上的图片
2021-05-09
将博客搬至CSDN
2021-05-09
elementUi源码解析(1)--项目结构篇
2021-05-09
将WCF迁移到gRPC
2021-05-09
EF Core 6.0的新计划
2021-05-09
自动遍历测试之Monkey工具
2021-05-09
Selenium Webdriver 架构
2021-05-09