c# vue 跨域get post cookie等问题
背景介绍:
开发微信公共号时前后端分离,后台用C#开发,前端使用vue框架,数据采用axios传输
具体问题:
1:前后端分离造成的跨域访问问题
2:跨域后cookie传输和设置问题
解决方案:
1:使用jsonp作为数据传输的方式,前端和后端配合解决跨域问题
2:通过设置webconfig配合axios.js解决cookie传输(get、set)
具体方案:
问题一:
1:controller
/// <summary>
/// get
/// </summary>
/// <param name="ID"></param>
/// <returns></returns>
public JsonpResult Text(int ID)
{
return this.Jsonp(ID);
}
/// <summary>
/// post
/// </summary>
/// <param name="jsonp"></param>
/// <returns></returns>
[HttpPost]
public JsonpResult TextJsonpHttp(string jsonp)
{
return this.Jsonp(jsonp);
}
2:JsonpResult
/// <summary>
/// Controller控制器类的扩展方法,即:Controller控制器下扩展一个Jsonp方法,这个方法带一个object类型的参数
/// </summary>
public static class ControllerExtension
{
public static JsonpResult Jsonp(this Controller controller, object data)
{
JsonpResult result = new JsonpResult()
{
Data = data,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
return result;
}
}
public class JsonpResult : JsonResult
{
public static readonly string JsonpCallbackName = "MoDoPMS";//js中设置的jsonp
public static readonly string CallbackApplicationType = "application/json";
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new AccessViolationException("context");
} if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) //如果不允许来自客户端的Get请求,并且请求类型是Get
{
throw new AccessViolationException();
}
var response = context.HttpContext.Response;
if (!string.IsNullOrEmpty(ContentType)) //这个ContentType是获取或设置内容的类型。它是JsonResult类中的一个属性
{
response.ContentType = ContentType; //设置响应内容的类型
}
else
{
response.ContentType = CallbackApplicationType; //设置响应内容的类型
}
if (ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;//设置响应内容的编码
} if (Data != null) //这个Data是JsonResult类中的一个属性
{
string buffer;
var request = context.HttpContext.Request;
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
if (request[JsonpCallbackName] != null) //获取回调函数名称
{
buffer = String.Format("{0}({1})", request[JsonpCallbackName], JsonConvert.SerializeObject(Data, Formatting.None, settings));//首先根据callback获取获取函数名,然后传入json字符串作为函数参数
}
else
{
buffer = JsonConvert.SerializeObject(Data, settings);//首先根据callback获取获取函数名,然后传入json字符串作为函数参数
}
response.Write(buffer);
}
}
}
3:vue中axios.js
var url="/Wechat/JsonP/GetVueBranchList";
this.$http({
method: 'get',
dataType: "jsonp",
jsonp: "MoDoPMS",//jsonp接口参数
timeout: ,//超时
url: url,
})
.then(function(response){ });
get
axios.post('/Wechat/JsonP/PostVueLogin', qs.stringify({loginphone:_this.phone,loginpwd:_this.password}))
.then(response => {
console.log(response);
let instance = Toast(response.data.Message);
setTimeout(() => {
instance.close();
_this.$router.push({name: response.data.Url});
}, );
})
.catch(err => {
console.log(err);
});
post
get与post均可使用axios.js
4:配置项web.config
<system.webServer>
<httpProtocol>
<customHeaders> <add name="Access-Control-Allow-Origin" value="*" /><!--解决跨域问题-->
<add name="Access-Control-Allow-Methods" value="POST,GET" /><!--解决提交方式问题-->
</customHeaders>
</httpProtocol>
</system.webServer>
web.config
问题二:
1:web.config中配置项
<system.webServer>
<httpProtocol>
<customHeaders>
<!--上线后将这里改为微信端的域名-->
<add name="Access-Control-Allow-Origin" value="http://localhost:8080" /><!--解决跨域问题-->
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" /><!--解决提交方式问题-->
<add name="Access-Control-Allow-Credentials" value="true" /><!--解决cookie问题-->
<add name="Access-Control-Max-Age" value=""/>
</customHeaders>
</httpProtocol>
</system.webServer>
很多人问题出在这里
The credentials mode of an XMLHttpRequest is controlled by the withCredentia
原因是将origin设置成*,*可以解决跨域问题,但是如果想配合使用cookie就必须设置固定域名,如果设置两个,则会有一个不起作用。这里参考了简书 CSDN 中的一些理论
2:vue-main.js中
axios.defaults.withCredentials = true//解决cookie问题
3:axios请求

4:http header

得到结论,在跨域的情况下使用 axios,首先需要配置 axios 的 withCredentials 属性为 true。然后服务器还需要配置响应报文头部的 Access-Control-Allow-Origin 和 Access-Control-Allow-Credentials 两个字段,Access-Control-Allow-Origin 字段的值需要为确定的域名,而不能直接用 ‘*’ 代替,Access-Control-Allow-Credentials 的值需要设置为 true。前端和服务端两边都配置完善之后就可以正常进行跨域访问以及携带 cookie 信息了。
c# vue 跨域get post cookie等问题的更多相关文章
- 跨域(cross-domain)访问 cookie (读取和设置)
Passport 一方面意味着用一个帐号可以在不同服务里登录,另一方面就是在一个服务里面登录后可以无障碍的漫游到其他服务里面去.坦白说,目前 sohu passport 在这一点实现的很烂(不过俺的工 ...
- [转]vue跨域解决方法
vue跨域解决方法 vue项目中,前端与后台进行数据请求或者提交的时候,如果后台没有设置跨域,前端本地调试代码的时候就会报“No 'Access-Control-Allow-Origin' hea ...
- vue跨域问题解决(生产环境)
vue跨域问题解决(使用webpack打包的) 配置代理:(config下index.js文件) module.exports = { dev: { env: require('./dev.env') ...
- vue跨域处理
本人对于vue跨域处理流程不是很清楚,特此理顺一遍. 1.在config中进行配置,该文件不是都存在,需要自己建: proxyTable,这个参数主要是一个地址映射表,你可以通过设置将复杂的url简化 ...
- 聊一下,前后分离后带来的跨域访问和cookie问题
在谈前后分离前,我们先看看什么是前后一体的.当我们用javaweb开发网站时,最终我们渲染的jsp或者springthymeleaf.我们的页面其实是WEB-INFO或者templates下.当用户请 ...
- node(koa2)跨域与获取cookie
欲做一个node 的网关服务,通过 cookie 做信息传递,选择框架 koa2,这里简单记录跨域处理以及 cookie 获取. 首先:解决跨域问题,使用 koa2-cros 来处理,跨域问题后端处理 ...
- vue 跨域 springCloud @CrossOrigin注解
vue 跨域 springCloud @CrossOrigin注解 一丶什么是跨域 跨域问题来源于浏览器的同源策略,浏览器为了提高网站的安全性,在发送ajax请求时,只有在当前页面地址与请求地址的协 ...
- vue踩坑(二):跨域以及携带cookie
最近后台需求要在请求的时候传cooki给后台,正常情况下拿到cookie后存在cookie里,同域名下是会自己带到请求头里的,但是因为要在本地调试,那么问题就来了,localhost:8080下面的c ...
- vue 跨域请求,后端cookie session取不到
虽然后端设置了可以跨域请求,但是后台设置到cookie中的session取不到!这时候mac电脑自己设置nginx代理! mac电脑系统重装了,记录一下安装nginx的过程: 1.打开终端(cmd) ...
随机推荐
- 登录首页时报错:java.lang.IllegalArgumentException (不合法的参数异常)
处理一个老项目,DOWN下项目并配好之后,启动没问题,但是登陆之后首页显示如下: 控制台报错如下: 严重: Servlet.service() for servlet jsp threw except ...
- Python-装饰器进阶
基本概念 具体概念请先看之前的文章 理解装饰器 装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志.性能测试.事务处理, Web权限校验, Cache等. 很有名的例子,就 ...
- 部署NopCommerce商城系统问题整理
NopCommerce是一个很棒的开源商城系统,下面整理一下我在部署使用NopCommerce系统中的一些问题. 我使用的是NopCommerce3.9版本. 1.安装 安装教程网上很多,这里不细说, ...
- C++之声明与定义的区别
直接举例,在C++中,声明与定义的区别如下: extern int a;//若有extern关键字,则只是声明 int b;//若没有extern关键字,则为声明+定义 int a;//若之前已经声明 ...
- APP消息推送功能
1.APP内部最好设计-我的消息-的功能,以便用户查看推送消息历史记录,通过角标.已读.未读等设计吸引用户读取消息.(画下来这都是重点) 2.建议提供推送设置功能,允许用户设置推送消息是否显示于通知栏 ...
- mysql安装在centos7报错ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
原文链接:http://blog.csdn.net/kuluzs/article/details/51924086 [问题]:mysql版本:5.7.13 首次在centos下安装MySQL,客户端连 ...
- NOPcommerce研究
http://www.cnblogs.com/gusixing/archive/2012/04/07/2435873.html
- EM5-PE6B
1. vocabulay 1.1 scary adj.令人恐怖的 This is a scary thing. you can construct some extremely scary scena ...
- RabbitMQ系列一
1.http://www.erlang.org/downloads 下载一个比教新的版本(otp_win64_20.2.exe) 2.http://www.rabbitmq.com/install-w ...
- Bootstrap学习笔记(1)栅格系统
栅格系统: .row 1行12列 .col-md-3 占3列,一行就是4个 <!DOCTYPE html> <html lang="en"> <hea ...