Vue - .NET Core 跨域

微软官网:https://docs.microsoft.com/zh-cn/aspnet/core/security/cors?view=aspnetcore-2.2

一、.NET Core WebApi 设置跨域

// Startup 配置
public void ConfigureServices(IServiceCollection services)
{
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
     //添加 Cors 跨域,
     services.AddCors(option =>
     {
          //添加一个名为 AllowAny 的策略
          option.AddPolicy("AllowAny", builder =>
          {
               //配置跨域项
               builder.AllowAnyHeader();
               builder.AllowAnyMethod();
               builder.AllowAnyOrigin();
               builder.AllowCredentials();
          });
     });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }
     //使用 Cors
     app.UseCors();
     app.UseMvc();
}
//控制器使用 [Route("api/demo")] [ApiController] [EnableCors("AllowAny")] //启用Cors跨域,这里可以建一个Api控制器的基类,不必每一个都写 public class DemoController : ControllerBase { // GET: api/<controller> [HttpGet("GetSomething")] public string GetSomething() { return "Elson Je"; } }

二、Vue-cli webpack 设置

//Demo
export default { name: 'demo', data(){ return { name:'' } }, created(){ let this_ = this; //正常写法 //axios.get('http://localhost:5000/ap/demo/getSomething').then(……) //webpack配置代理 axios.get('/api/demo/getSomething').then((res)=>{ this_.name = res.data; }) } } //config -> index.js -> proxyTable 配置
//前端也可以配置跨域,具体请查阅资料,这里只配置了代理 proxyTable: { '/api': { target: 'http://localhost:5000', pathRewrite: { '^api': '/' } } },

三、注意事项

1.设置跨域后有一定的安全风险,例如XSS攻击,微软文档写的很详细 (虽然机翻有点好笑,有能力的朋友可以阅读原文)

谦良恭卑,信诚实至;生活不易,共勉同求。

猜你喜欢

转载自www.cnblogs.com/elsonww/p/11397207.html