jQuery+ASP.NET MVC基于CORS实现带cookie的跨域ajax请求

这是今天遇到的一个实际问题,在这篇随笔中记录一下解决方法。

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) {
        //...
    }
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值