jQuery+ASP.NET MVC基于CORS实现带cookie的跨域ajax请求
2016-05-28 17:19
441 查看
这是今天遇到的一个实际问题,在这篇随笔中记录一下解决方法。
ASP.NET Web API提供了CORS支持,但ASP.NET MVC默认不支持,需要自己动手实现。可以写一个用于实现CORS的ActionFilterAttribute,我们就是这么实现的:
在需要支持CORS的Controller Action上加上[AllowCors("www.cnblogs.com")]标记。
jquery ajax的请求代码如下:
【遇到的问题】
1)一开始在ajax代码中没加"withCredentials: true",发现ajax请求中没带上cookies。
2)加了"withCredentials: true"后,服务端响应出错:
后来在服务端添加了如下的响应头解决了问题:
3)如果是http post,ajax的请求参数中contentType不能用applicaion/json,要用application/x-www-form-urlencoded。
ASP.NET Web API提供了CORS支持,但ASP.NET MVC默认不支持,需要自己动手实现。可以写一个用于实现CORS的ActionFilterAttribute,我们就是这么实现的:
public class AllowCorsAttribute : ActionFilterAttribute { private string[] _domains; public AllowCorsAttribute(string domain) { _domains = new string[] { domain }; } public AllowCorsAttribute(string[] domains) { _domains = domains; } public override void OnActionExecuting(ActionExecutingContext filterContext) { var context = filterContext.RequestContext.HttpContext; var host = context.Request.UrlReferrer?.Host; if (host != null && _domains.Contains(host)) { context.Response.AddHeader("Access-Control-Allow-Origin", $"http://{host}"); context.Response.AddHeader("Access-Control-Allow-Credentials", "true"); } base.OnActionExecuting(filterContext); }
在需要支持CORS的Controller Action上加上[AllowCors("www.cnblogs.com")]标记。
jquery ajax的请求代码如下:
$.ajax({ url: '...', type: 'get', xhrFields: { withCredentials: true }, dataType: 'application/json; charset=utf-8', success: function (data) { //... } });
【遇到的问题】
1)一开始在ajax代码中没加"withCredentials: true",发现ajax请求中没带上cookies。
2)加了"withCredentials: true"后,服务端响应出错:
XMLHttpRequest cannot load '{url}'. Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://www.cnblogs.com' is therefore not allowed access.
后来在服务端添加了如下的响应头解决了问题:
context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
3)如果是http post,ajax的请求参数中contentType不能用applicaion/json,要用application/x-www-form-urlencoded。
$.ajax({ url: 'cross domain url', data: { reason: txtReason }, contentType: 'application/x-www-form-urlencoded; charset=utf-8', type: 'post', dataType: 'json', xhrFields: { withCredentials: true }, success: function (data) { //... } });
相关文章推荐
- Jquery 插件\Js 插件收集
- jquery模拟淘宝购物车
- jQuery学习笔记20160528
- jquery ajax cache的问题
- jquery 实现 点击按钮后倒计时效果,多用于实现发送手机验证码、邮箱验证码
- jQuery源码学习(二)
- jquery购物车数量加减
- 《Javascript、jQuery获取各种屏幕的宽度和高度方法》
- javascript、jQuery操作数组
- js jquery 实现html页面之间参数传递(单一参数、对象参数传递)
- Jquery easyUI datagrid加载复杂JSON数据方法
- 浅谈jQuery 中的事件冒泡和阻止默认行为
- jquery取消事件冒泡的三种方法(推荐)
- JQuery animate 动画效果出现抖动的解决办法
- jqueryMobile 动态添加元素,展示刷新视图的实现方法
- jQuery Mobile动态刷新页面样式的实现方法
- JQuery EasyUI Layout 在from布局自适应窗口大小的实现方法
- jquery--操作html
- jQuery操作动态生成的内容的方法
- jQuery控制li上下循环滚动插件用法实例(附demo源码下载)