Skip to content

Instantly share code, notes, and snippets.

@RoLYroLLs
Created March 2, 2018 22:54
Show Gist options
  • Save RoLYroLLs/b1b962f661c8d348b4b6184849a6f904 to your computer and use it in GitHub Desktop.
Save RoLYroLLs/b1b962f661c8d348b4b6184849a6f904 to your computer and use it in GitHub Desktop.
using System;
using System.Web.Mvc;
using Newtonsoft.Json;
public class JsonNetResult : JsonResult {
public JsonSerializerSettings SerializerSettings { get; set; }
public Formatting Formatting { get; set; }
public JsonNetResult(object data) {
this.JsonRequestBehavior = JsonRequestBehavior.DenyGet;
this.SerializerSettings = new JsonSerializerSettings();
this.Data = data;
}
public JsonNetResult(object data, Formatting formatting) : this(data) {
this.Formatting = formatting;
}
public override void ExecuteResult(ControllerContext context) {
if (context == null)
throw new ArgumentNullException(nameof(context));
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("Get not allowed.");
var response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
if (this.ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
if (this.Data == null)
return;
using (var jsonWriter = new JsonTextWriter(response.Output) { Formatting = Formatting }) {
var jsonSerializer = JsonSerializer.Create(SerializerSettings);
jsonSerializer.Serialize(jsonWriter, Data);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment