using System; using System.Web.Mvc; using System.Web.Script.Serialization; namespace FHT.Agency.Web.Extensions { public class JsonpResult : JsonResult { private const string JsonpCallbackName = "callback"; private const string CallbackApplicationType = "application/json"; /// /// Enables processing of the result of an action method by a custom type that inherits from the class. /// /// The context within which the result is executed. /// The parameter is null. /// is null. /// public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if ((JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET")) { throw new InvalidOperationException(); } System.Web.HttpResponseBase response = context.HttpContext.Response; if (!string.IsNullOrEmpty(ContentType)) { response.ContentType = ContentType; } else { response.ContentType = CallbackApplicationType; } if (ContentEncoding != null) response.ContentEncoding = this.ContentEncoding; if (Data != null) { string buffer; System.Web.HttpRequestBase request = context.HttpContext.Request; var serializer = new JavaScriptSerializer(); if (request[JsonpCallbackName] != null) { buffer = string.Format("{0}({1})", request[JsonpCallbackName], serializer.Serialize(Data)); } else { buffer = serializer.Serialize(Data); } response.Write(buffer); } } } }