Skip to content

Instantly share code, notes, and snippets.

@PizzaConsole
Created August 7, 2020 20:59
Show Gist options
  • Save PizzaConsole/d73ad829741cbef4ebb90b1e6a8864e4 to your computer and use it in GitHub Desktop.
Save PizzaConsole/d73ad829741cbef4ebb90b1e6a8864e4 to your computer and use it in GitHub Desktop.
Use Custom Json Serialization Setting per Controller in ASP.NET Core 3.0+
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Formatters;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Buffers;
namespace MyProject.Filters
{
//Resources:
//https://stackoverflow.com/questions/51769415/configure-input-output-formatters-on-controllers-with-asp-net-core-2-1
//https://stackoverflow.com/questions/59634633/alternatives-to-jsonoutputformatter-in-asp-net-core-3-1-at-controller-level
//Note Filters are only called on Controller class not ControllerBase class
public class CustomResultFilterAttribute : Attribute, IResultFilter
{
public void OnResultExecuted(ResultExecutedContext context)
{
}
public void OnResultExecuting(ResultExecutingContext context)
{
if (context.Result is ObjectResult objectResult)
{
var serializerSettings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver(),
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
var mvoptions = new MvcOptions();
var jsonFormatter = new NewtonsoftJsonOutputFormatter(
serializerSettings,
ArrayPool<char>.Shared, mvoptions);
objectResult.Formatters.Add(jsonFormatter);
}
}
}
}
using MyProject.Filters;
using Microsoft.AspNetCore.Mvc;
namespace MyProject.Controllers
{
[ApiController]
[CustomResultFilter]
public class CustomController : Controller
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment