Skip to content

Instantly share code, notes, and snippets.

@codedecay
Forked from jpoehls/BaseController.cs
Last active August 29, 2015 14:27
Show Gist options
  • Save codedecay/f74f3b2be068f1a28af4 to your computer and use it in GitHub Desktop.
Save codedecay/f74f3b2be068f1a28af4 to your computer and use it in GitHub Desktop.
Newtonsoft Json Results for MVC
using System;
using System.Linq;
using System.Web.Mvc;
public abstract class BaseController : Controller
{
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding)
{
return new JsonNetResult
{
ContentType = contentType,
ContentEncoding = contentEncoding,
Data = data
};
}
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonNetResult
{
ContentType = contentType,
ContentEncoding = contentEncoding,
Data = data,
JsonRequestBehavior = behavior
};
}
}
using System;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
/// <summary>
/// A <see cref="JsonResult"/> implementation that uses JSON.NET to
/// perform the serialization.
/// </summary>
public class JsonNetResult : JsonResult
{
// public JsonRequestBehavior JsonRequestBehavior { get; set; }
// public Encoding ContentEncoding { get; set; }
// public string ContentType { get; set; }
// public object Data { get; set; }
public JsonSerializerSettings SerializerSettings { get; set; }
public Formatting Formatting { get; set; }
public JsonNetResult()
{
Formatting = Formatting.None;
SerializerSettings = new JsonSerializerSettings();
JsonRequestBehavior = JsonRequestBehavior.DenyGet;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet
&& String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
}
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(ContentType)
? ContentType
: "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Data != null)
{
var writer = new JsonTextWriter(response.Output) { Formatting = Formatting };
var serializer = JsonSerializer.Create(SerializerSettings);
serializer.Serialize(writer, Data);
writer.Flush();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment