• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
遗忘的小猪
海内存知己,天涯若比邻
博客园    首页    新随笔    联系   管理    订阅  订阅
.net core webapi+vue 跨域访问

最近在做一个前后端分离的示例,以下代码完美解决跨域的问题

一、后端服务

1.首先我们建一个.net core webapi的项目

2.项目引用Microsoft.AspNetCore.Cors 包

3.添加cors 服务

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //添加cors 服务
            services.AddCors(options =>//p.WithOrigins这里就是配置策略,允许访问的地址
        options.AddPolicy("Admin", p => p.WithOrigins("http://localhost:5000", "http://localhost:9528").AllowAnyMethod().AllowAnyHeader().AllowCredentials()) ); }

4.配置Cors

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            //配置Cors
            app.UseCors("Admin");
            app.UseHttpsRedirection();
            app.UseMvc();
        }

5.编写控制器

 [Route("api/[controller]")]
    [ApiController]
    public class GetDataController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        [EnableCors("Admin")]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { DateTime.Now.ToString() };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }

  

二、前段

1.创建Vue前段项目,我这里是使用的是vue+element (自己百度创建)

2.安装axios模块 npm install axios -g

3.调用api

export default {

data() {
return {
msg:''
}
},
methods: {
onSubmit() {
let _self=this;
console.log(this.form)
axios.get('http://localhost:5000/api/GetData')

.then(function (response) {
console.log(response);
_self.msg=response.data;
})
.catch(function (error) {

console.log(error);

});
}
}
}

  

posted on 2018-10-11 17:53  一杯敬明天一杯敬过往  阅读(4080)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3