让web api 4.5支持Jquery.getJson(url,handle)跨域访问

代码片段,google了半天,找到的都是4.5 rc,或之前版本的代码,发现都不能用,正式版后有些方法做了修改。我重新修改一下分享给大家

public static class HttpRequestMessageExtensions
    {
        public static string QueryString(this HttpRequestMessage request, string name)
        {
            string requestUri = request.RequestUri.Query;
            string[] queries = requestUri.Split('&');

            foreach (string s in queries)
            {
                if (s.Contains(name))
                {
                    int index = s.IndexOf('=');
                    int stopIndex = s.IndexOf('&', index);
                    if (stopIndex != -1)
                        return s.Substring(index + 1, stopIndex - index - 1);
                    else
                        return s.Substring(index + 1, s.Length - index - 1);
                }
            }

            return string.Empty;
        }
    }
    public class JsonpMediaTypeFormatter : JsonMediaTypeFormatter
    {
        private string callbackQueryParameter;
        private HttpRequestMessage httpRequest;
        public JsonpMediaTypeFormatter()
        {
            SupportedMediaTypes.Add(DefaultMediaType);
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));

            MediaTypeMappings.Add(new UriPathExtensionMapping("jsonp", DefaultMediaType));
        }

        public string CallbackQueryParameter
        {
            get { return callbackQueryParameter ?? "callback"; }
            set { callbackQueryParameter = value; }
        }
        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
        {
            httpRequest = request;
            return base.GetPerRequestFormatterInstance(type, request, mediaType);
        }
        public override Task WriteToStreamAsync(
              Type type, object value, Stream stream, HttpContent content, TransportContext transportContext)
        {
            string callback;

            if (IsJsonpRequest(out callback))
            {
                return Task.Factory.StartNew(() =>
                {
                    var writer = new StreamWriter(stream);
                    writer.Write(callback + "(");
                    writer.Flush();

                    base.WriteToStreamAsync(type, value, stream,content, transportContext).Wait();

                    writer.Write(")");
                    writer.Flush();
                });
            }
            else
            {
                return base.WriteToStreamAsync(type, value, stream, content, transportContext);
            }
        }


        private bool IsJsonpRequest(out string callback)
        {
            callback = null;

            //if (HttpContext.Current.Request.HttpMethod != "GET")
            if(httpRequest.Method!=HttpMethod.Get)
                return false;
            //var uri = httpRequest.RequestUri;
            //var query = uri.Query;
            callback = httpRequest.QueryString(CallbackQueryParameter);

            return !string.IsNullOrEmpty(callback);
        }
    } 

  

var config = new HttpSelfHostConfiguration(baseAddress);
    
               // Set the max message size to 1M instead of the default size of 64k and also
               // set the transfer mode to 'streamed' so that don't allocate a 1M buffer but 
               // rather just have a small read buffer.
               config.MaxReceivedMessageSize = 1024 * 1024;
               config.TransferMode = TransferMode.Streamed;
               config.Formatters.Insert(0, new JsonpMediaTypeFormatter());

  

$('#getjson').bind('click', function () {
            $.getJSON("http://192.168.103.135:8080/api/products/1?jsoncallback=?",
                function (data) {
                    $("#result").append(data);
                    return;
                    $("#result").append(data.Image);
                    $("<img/>").attr("src", "data:image/jpeg;base64," + data.Image).appendTo("#result");
                    return;
                    $.each(data, function (i, item) {
                        $("#result").append(item.Name);
                        $("<img/>").attr("src", item.Image).appendTo("#result");

                    });
                });
        });

  

posted @ 2013-01-07 10:38  阿新  阅读(1566)  评论(1编辑  收藏  举报