Skip to content

Instantly share code, notes, and snippets.

@rorymurphy
Created May 13, 2015 18:43
Show Gist options
  • Select an option

  • Save rorymurphy/a78bcadfd0120e4e38b4 to your computer and use it in GitHub Desktop.

Select an option

Save rorymurphy/a78bcadfd0120e4e38b4 to your computer and use it in GitHub Desktop.
JSON.NET ActionResult for ASP.NET MVC (using JSON extensions)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
namespace Xintricity.Web.Mvc
{
public class JsonNetResult : JsonResult
{
public JsonNetResult()
{
Settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Error,
TypeNameHandling = TypeNameHandling.None
};
}
public JsonSerializerSettings Settings { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("JSON GET is not allowed");
HttpResponseBase 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 sw = new StringWriter())
{
response.Write(this.Data.ToJSON(true));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment