问题如标题:APS.NET Core前后端分离开发中的跨域问题解决
其实APS.NET Core对跨域已经做了很好的支持和优化了
使用过APS.NET Framework开发并做过跨域支持的小伙伴就应该很清楚
这配置,那配置,到处都是配置,很繁琐
那现在来看看APS.NET Core到底有多简单吧
前后端分离中的跨域问题三步解决
//注册服务
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o=>o.AddPolicy("any",p=>p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod())); //services.AddCors(o=>o.AddPolicy("any",p=>p.WithOrigins(["https://www.baidu.com","https://www.baidu.com"])().AllowAnyHeader().AllowAnyMethod()));
//AllowAnyOrigin()允许所有域名跨域、WithOrigins()允许指定域名跨域
services.AddControllers();
}
//使用服务
public void Configure(IApplicationBuilder app,IwebHostEnvironment env)
{
// ......
app.UseCors();
// .....
}
//改造API接口
[EnableCors("any")] //绑定指定跨域方案
[Route("api/[controller]/[action]")]
[ApiController]
public class ProductsController:ControllerBase
{
//[EnableCors("any")]
public List<Products> GetProducts()
{
List<Products> products = new List<Products>();
//......
return products;
}
}