码迷,mamicode.com
首页 > Windows程序 > 详细

ASP.NET Web API 跨域访问(CORS)要注意的地方

时间:2015-07-03 12:01:26      阅读:682      评论:0      收藏:0      [点我收藏+]

标签:

一、客户端用JSONP请求数据

 

如果你想用JSONP来获得跨域的数据,WebAPI本身是不支持javascript的callback的,它返回的JSON是这样的:

{"YourSignature": "嫁人要嫁程序员,钱多话少死得早"}

然而,JSONP请求期望得到这样的JSON:

jQuery123456({"YourSignature": "嫁人要嫁程序员,钱多话少死得早"})

所以我们需要对WebAPI做拓展,让它支持这样的callback。我找到了两种办法。

自己写个Attribute,来给返回的JSON包上callback

 

public class JsonCallbackAttribute : ActionFilterAttribute
{
    private const string CallbackQueryParameter = "callback";

    public override void OnActionExecuted(HttpActionExecutedContext context)
    {
        var callback = string.Empty;

        if (IsJsonp(out callback))
        {
            var jsonBuilder = new StringBuilder(callback);
            jsonBuilder.AppendFormat("({0})", context.Response.Content.ReadAsStringAsync().Result);
            context.Response.Content = new StringContent(jsonBuilder.ToString());
        }
        base.OnActionExecuted(context);
    }

    private bool IsJsonp(out string callback)
    {
        callback = HttpContext.Current.Request.QueryString[CallbackQueryParameter];
        return !string.IsNullOrEmpty(callback);
    }
}

 

然后在要被调用的方法前加上这个Attribute:

        [JsonCallback]
        [HttpGet]
        public HttpResponseMessage a()
        {
            string strJson = "{\"info\" : \"true\"}";
            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(strJson, Encoding.UTF8, "text/plain")
            };
            return result;
        }

 

非常简洁明了,但是这种方法有个缺点,就是被加了[JsonCallback]的方法,只能适用于JSONP的请求。如果你希望API能被各种场合的客户端调用,还是在服务端提供支持吧。

2. 通过自定义JsonMediaTypeFormatter实现

 

参见 Artech大神的文章:http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-03.html

 

支持CORS最地道的方法当然是在服务端提供支持,按官网的办法,100%成功。http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

 

主要步骤是:

1. 到nuget上装一个包:http://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors/

2. 在WebApiConfig.Register方法中加入代码:

config.EnableCors();

3. 在Controller上加上Attribute:

[EnableCors(origins: "http://myclient.azurewebsites.net", headers: "*", methods: "*")]

这个域名是可以配置的,具体还请参考上面给出的官网教程。

最后,还要告诉大家一个坑,在服务端完提供支持以后,不要高兴的太早,如果你用jQuery.ajax()的方式去请求,还是会爆的:

$.ajax({
    url: yourCORSurl,
    data: ‘‘,
    dataType: json,
    type: GET,
    contentType: application/json; charset=utf-8,
    ...
})

经过无数次爆破,终于发现,只要把dataType和contentType两个参数去掉,就肯定不会爆了!!!

ASP.NET Web API 跨域访问(CORS)要注意的地方

标签:

原文地址:http://www.cnblogs.com/tinya/p/4618062.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!