Vue+C# MVC API前后端分离跨域设置

1. C#后端代码

Ps:添加一个过滤器(或者配置Web.config)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Blog.Filter
{
    public class HttpHeadAttribute: ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
            	//设置源
                string origin = filterContext.HttpContext.Request.Headers.Get("origin").ToString();
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", origin);
                filterContext.RequestContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Methods", "GET,POST, PUT, DELETE");
                filterContext.RequestContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Headers", "*");
                filterContext.RequestContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");

            }
            catch (Exception)
            {

                
            }
           
            
        }
    }
}

2. 前端Vue

Ps:在config/Index.js下 dev节点下添加代理

proxyTable: {  
      '/api': {  // 使用"/queue-admin"来代替 API头部,可随意命名 {}的内容
          //target: 'http://192.168.11.12:8080',  // 源地址 本地开发的API头部
          target: "https://{IP}:{端口}",  // 配置到服务器后端的API头部
          pathRewrite: { 
              '^/api': ''  // 路径重写,第一个与上面相同,第二个/queue-admin 为server.context-path(服务器的上下文)
          },
          // 以下解决https 访问问题。上面的可以访问http
          changeOrigin: true,
          secure: false,
          headers: {
            Referer: 'https://{IP}:{端口}'
          }
      }
  }

这样就可以实现跨域访问了。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值