zoukankan      html  css  js  c++  java
  • ASP.NET Web API 跨域访问(CORS)要注意的地方

    一、客户端用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

    蒋大神的文章的JsonpMediaTypeFormatter类只适合将对象传过去进行json序列化,有点弊端

    支持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两个参数去掉,就肯定不会爆了!!!

  • 相关阅读:
    Linux中断管理 (2)软中断和tasklet
    Linux中断管理 (1)Linux中断管理机制
    Linux中断管理
    Linux内核访问用户空间文件:get_fs()/set_fs()的使用
    Linux进程管理 (1)进程的诞生
    Linux进程管理专题
    Linux内存管理 (23)一个内存Oops解析
    Linux内存管理 (22)内存检测技术(slub_debug/kmemleak/kasan)
    Linux内存管理 (21)OOM
    Linux内存管理 (20)最新更新和展望
  • 原文地址:https://www.cnblogs.com/tinya/p/4618062.html
Copyright © 2011-2022 走看看