C# MVC jsonp初接触成功
利用jsonp进行跨域请求资源
C# MVC ApiControllers准备如下:
1、需要在引用处右键管理NuGet安装jsonp插件
2、在Application_Start()中配置
GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter(new JsonMediaTypeFormatter()));
3、在ApiControllers中写服务端接口代码
[HttpGet] public void H5PlusTextJsAjax( string callback = "") {
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.ContentType = "application/json"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; List<ReturnJosn> callbackjson = new List<ReturnJosn>(); callbackjson.Add( new ReturnJosn() { name = "fhjson" }); HttpContext.Current.Response. Write(HttpContext.Current.Request.Params["callbackparam"].ToString() + "(" + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(callbackjson) + ")"); HttpContext.Current.Response.End(); //return HttpContext.Current.Request.Params["callbackparam"].ToString() + // "(" + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(callbackjson) + ")"; }
4、在其他页面写前台代码
$.ajax({ type : "get", async:false, url : "http://localhost:11462/api/RePass", dataType : "jsonp", data:"{}", jsonp: "callbackparam",//服务端用于接收callback调用的function名的参数 success : function(json){ alert(json[0].name); }, error:function(httpstatesss,b11,c111){ alert('fail'); } });
测试成功。需要注意apicontrollers中写入返回流文本的json字符串一定要包含jq callback的随机名字JQuerxxxxxx(你的json字符串)。不然你的请求success但是会进入error里面。jq解析json不成功会抛出parseerror。"jQuery191002365952031686902_1436757310853 was not called"