Jsonp类

 public class JsonpResult : JsonResult
    {
        public JsonpResult()
        {
            this.Callback = "callback";
        }

        public JsonpResult(string callback)
        {
            this.Callback = callback;
        }

        /// <summary>
        /// Jsonp 回调的 function 名称,默认为 callback
        /// </summary>
        public string Callback { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            var request = context.HttpContext.Request;
            var response = context.HttpContext.Response;
            string jsoncallback = (context.RouteData.Values[this.Callback] as string) ?? request[this.Callback];
            if (!string.IsNullOrEmpty(jsoncallback))
            {
                if (string.IsNullOrEmpty(base.ContentType))
                {
                    base.ContentType = "application/x-javascript";
                }
                response.Write(string.Format("{0}(", jsoncallback));

     
                response.Headers.Add("P3P", "CP=CAO PSA OUR");
            }
            base.ExecuteResult(context);
            if (!string.IsNullOrEmpty(jsoncallback))
            {
                response.Write(")");
            }
        }
    }

 

调用方法

 [HttpGet]
        public JsonpResult GetComContent( string key)
        {
            string data = "hi:"+key;

            return new JsonpResult() { Data = data, JsonRequestBehavior = JsonRequestBehavior.AllowGet };

        }

 

posted @ 2016-07-29 20:27  zslm___  阅读(245)  评论(0编辑  收藏  举报