Skip to content

Instantly share code, notes, and snippets.

@jimbolla
Created October 17, 2018 13:35
Show Gist options
  • Save jimbolla/4feb9cf52b24829a7398ea6af9435acf to your computer and use it in GitHub Desktop.
Save jimbolla/4feb9cf52b24829a7398ea6af9435acf to your computer and use it in GitHub Desktop.
ResultAsJsonAttribute.cs
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Whatever
{
public class ResultAsJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var result = context.ActionDescriptor.Execute(context, context.ActionParameters);
context.Result = result is ActionResult actionResult
? actionResult
: new JsonNetResult(result);
}
}
public class JsonNetResult : ActionResult
{
private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
private readonly object _data;
public JsonNetResult(object data)
{
_data = data;
}
public override void ExecuteResult(ControllerContext context)
{
var json = JsonConvert.SerializeObject(_data, Settings);
var response = context.HttpContext.Response;
response.ContentType = "application/json; charset=utf-8";
response.Write(json);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment