跨域问题的出现,简而言之就是基于浏览器同源策略而反馈出来的一种安全机制,是前端开发调用中出现的一种十分常见的问题,且解决方法有多种,比如采用Nginx做代理服务器,或者在前端使用自己的代理服务器,或者是直接在后端设置允许跨域,这里采用的是最后一种解决手段。
环境说明:netcore 3.1
代码部分
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
//支持mvc服务
services.AddControllersWithViews();
//允许所有跨域
services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder.AllowAnyMethod()
.SetIsOriginAllowed(_ => true)
.AllowAnyHeader()
.AllowCredentials();
}));
}
然后接着在Configure中启用
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//启用路由
app.UseRouting();
//允许所有跨域
app.UseCors("CorsPolicy");
app.UseEndpoints(endpoints =>
{
app.UseEndpoints(endpoints =>
{
//属性路由
endpoints.MapControllers();
});
});
}
测试
HomeController
[Route("Home")]
public class HomeController : Controller
{
[Route("")]
[Route("Index")]
[HttpGet]
public IActionResult Index()
{
return Content("Home index");
}
}
前端走一个axios
this.axios
.get("https://localhost:5001/Home")
.then(
(response) => {
console.log(response);
},
(error) => {
console.log(error.message);
}
);
只要控制台没有爆CORS的错误就说明成功了