using System; using System.IO; using System.Web; using System.Web.Mvc; using Newtonsoft.Json; namespace WebInterface.Helpers { /// /// Custom JSON action result using JSON.NET library /// public class JsonNetResult : JsonResult { /// /// Serialization settings /// public JsonSerializerSettings Settings { get; } /// /// Constructor /// public JsonNetResult() { Settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Error }; } /// /// Generates the resulting JSON output /// /// Controller context for outputting public override void ExecuteResult(ControllerContext context) { //Verify context is valid before continuing if (context == null) { throw new ArgumentNullException(nameof(context)); } //Verify HTTP method is valid before continuing if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("JSON GET is not allowed"); } //Write response HttpResponseBase response = context.HttpContext.Response; response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType; if (ContentEncoding != null) response.ContentEncoding = ContentEncoding; if (Data == null) return; var scriptSerializer = JsonSerializer.Create(Settings); using (var sw = new StringWriter()) { scriptSerializer.Serialize(sw, Data); response.Write(sw.ToString()); } } } }