netcore 解决跨域问题(rush_peng)

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()
        {
            List<Product> products = new List<Product>
            {
            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】https://www.cnblogs.com/lxhbky/p/11128217.html
【2】https://www.cnblogs.com/dotnet261010/p/10177166.html

posted @ 2020-10-04 19:17  沧海一声笑rush  阅读(141)  评论(0编辑  收藏  举报