ASP.NET MVC中实现JSONP
只是了解下新东西,Access-Control-Allow-Origin 不是所以浏览器都支持。
Refer:
跨域资源共享的10种方式:http://www.woiweb.net/10-cross-domain-methods.html
asp-net-mvc-returning-jsonp: http://stackoverflow.com/questions/758879/asp-net-mvc-returning-jsonpajax-cross-origin-http-request : http://www.oschina.net/translate/ajax-cross-origin-http-request
Code:
using System.Web.Mvc; /// <summary> /// JSONP 跨域 /// </summary> public class JsonpResult : JsonResult { public string Callback { get; set; } public JsonpResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet; } public override void ExecuteResult(ControllerContext context) { var httpContext = context.HttpContext; var callback = Callback; if (string.IsNullOrWhiteSpace(callback)) callback = httpContext.Request["callback"]; httpContext.Response.Write(callback + "("); base.ExecuteResult(context); // httpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*"); httpContext.Response.Write(");"); } } // GET: /Jsonp/ public ActionResult Index() { var user = new { Name = "Irving", Age = "23" }; return new JsonpResult {Data = user }; }
XML配置
<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol> </system.webServer>
JS
@{ ViewBag.Title = "Test CrossDomain"; } <h2> Test</h2> @section scripts{ <script type="text/javascript"> $(function () { $.ajax({ type: "GET", url: "http://localhost:89/Jsonp/Index", dataType: "jsonp", success: function (result) { console.log(result); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log("Error: " + errorThrown); } }); }); //测试WCF跨域 $(function () { $.ajax({ type: "GET", url: "http://172.23.100.99/HotelService/Rest/GetAllPriceAndRmFlow/800822/2345678976543456789/2013-12-10/2013-12-11/0210B6/JSON", dataType: "jsonp", success: function (result) { console.log(result); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log("Error: " + errorThrown); } }); }); </script> }