asp.net web api2.0 ajax跨域解决方案

Web Api的优缺点就不说了,直接说怎么跨域,我搜了一下,主要是有两种。

 一,ASP.NET Web API支持JSONP,分两种

  1,利用JsonMediaTypeFormatter,具体参考这里:http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-03.html

上代码:

新建JsonpMediaTypeFormatter类:

 

    public class JsonpMediaTypeFormatter : JsonMediaTypeFormatter { private string callbackQueryParameter; 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; } } /// <summary>

        /// 将对象序列化后的JSON字符串填充到JavaScript回调函数中 /// </summary>

        /// <param name="type"></param>

        /// <param name="value"></param>

        /// <param name="stream"></param>

        /// <param name="content"></param>

        /// <param name="transportContext"></param>

        /// <returns></returns>

        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); } } /// <summary>

        /// 判断是否为跨域请求 /// </summary>

        /// <param name="callback"></param>

        /// <returns></returns>

        private bool IsJsonpRequest(out string callback) { callback = null; if (HttpContext.Current.Request.HttpMethod != "GET") return false; callback = HttpContext.Current.Request.QueryString[CallbackQueryParameter]; return !string.IsNullOrEmpty(callback); } }

 

  • 在Global.asax中注册JsonpMediaTypeFormatter
  • GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter());
    1.  

  2,利用ActionFilterAttribute ,具体参考这里:http://stackoverflow.com/questions/9421312/jsonp-with-asp-net-web-api/18206518#18206518

  代码:

新建 JsonCallbackAttribute 类

    public class JsonCallbackAttribute : ActionFilterAttribute { private const string CallbackQueryParameter = "callback"; public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { var callback = string.Empty; if (IsJosnp(out callback)) { var jsonBuilder = new StringBuilder(callback); jsonBuilder.AppendFormat("({0})", actionExecutedContext.Response.Content.ReadAsStringAsync().Result); actionExecutedContext.Response.Content = new StringContent("C(\"a\")"); } base.OnActionExecuted(actionExecutedContext); } private bool IsJosnp(out string callback) { callback = System.Web.HttpContext.Current.Request.QueryString[CallbackQueryParameter]; return !string.IsNullOrEmpty(callback); } }

在Global.asax中注册JsonCallbackAttribute

GlobalConfiguration.Configuration.Filters.Add(new JsonCallbackAttribute());

 

 

 二,使用 Microsoft ASP.NET Web API 2 Cross-Origin Suppor

  使用 NuGe 安装 Microsoft ASP.NET Web API 2 Cross-Origin Support,这里说的很详细

  然后在Global.asax中开启针对CORS的支持,EnableCors加不加无影响的样子。

 

测试实例:

<!DOCTYPE html>



<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <script src="http://cdn.bootcss.com/jquery/2.1.3/jquery.min.js"></script>

    <title>测试 WebApi 跨域</title>

</head>

<body>

    <form id="form1" runat="server">

        <input type="button" id="btnGet" value="Get 点击跨域查询数据" />

        <div id="bindData">

        </div>

        <input type="button" id="btnPost" value="Post 点击跨域查询数据" />

    </form>

    <script> $('#btnGet').bind('click', function (e) { $.ajax({ type: "GET", url: "http://localhost:20128/api/UserInfo", success: function (data) { var html = ""; $.each(data, function (index, val) { html += "<ul><li>GroupName: " + val.Id + " -- " + val.Name + "</li></ul>"; }); $("#bindData").append(html); } }); }); $('#btnPost').bind('click', function (e) { var user = { Id: '1', Name: '233' }; $.ajax({ type: "POST", contentType: 'application/json; charset=utf-8', data: JSON.stringify(user), url: "http://localhost:20128/api/UserInfo", success: function (data) { //var html = ""; //$.each(data, function (index, val) { // html += "<ul><li>GroupName: " + val.Id + " -- " + val.Name + "</li></ul>"; //}); //$("#bindData").append(html);

 } }); }); </script>

</body>

</html>

 

Ajax请求在Post数据的时候,一定要加上这样项:

contentType: 'application/json; charset=utf-8', data: JSON.stringify(user),

 

就这样,只是把网络上有解决方案的整理了一下,放在了一切。

你可能感兴趣的:(asp.net)