码迷,mamicode.com
首页 > Web开发 > 详细

MVC上的jsonp扩展,解决跨域访问问题

时间:2018-05-14 10:26:45      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:str   ring   app   name   blank   response   理论   ack   代码   

总是有人会遇到跨域问题,然后有个jsonp的解决方案,MVC中代码如下:

public class JsonpResult : System.Web.Mvc.JsonResult
    {
        object data = null;

        public JsonpResult()
        {
        }

        public JsonpResult(object data)
        {
            this.data = data;
        }

        public override void ExecuteResult(ControllerContext controllerContext)
        {
            if (controllerContext != null)
            {
                HttpResponseBase Response = controllerContext.HttpContext.Response;
                HttpRequestBase Request = controllerContext.HttpContext.Request;

                string callbackfunction = Request["callback"];
                if (string.IsNullOrEmpty(callbackfunction))
                {
                    throw new Exception("Callback function name must be provided in the request!");
                }
                Response.ContentType = "application/x-javascript";
                if (data != null)
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    Response.Write(string.Format("{0}({1});", callbackfunction, serializer.Serialize(data)));
                }
            }
        }

    }

理论上还可以自己扩展json的解析方式,比如你觉得默认的json解析器太慢什么的。

MVC上的jsonp扩展,解决跨域访问问题

标签:str   ring   app   name   blank   response   理论   ack   代码   

原文地址:https://www.cnblogs.com/RainbowInTheSky/p/9034584.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!