Created
October 17, 2018 13:35
-
-
Save jimbolla/4feb9cf52b24829a7398ea6af9435acf to your computer and use it in GitHub Desktop.
ResultAsJsonAttribute.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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