Add switch Json Serializer capability

This commit is contained in:
Khanhnguyen
2021-02-21 18:55:26 +07:00
parent 29d130cc21
commit dd807a80a3
2 changed files with 23 additions and 3 deletions

View File

@@ -13,21 +13,32 @@ namespace SilkierQuartz.Controllers
#region Target-Specific Directives
#if ( NETSTANDARD || NETCOREAPP )
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Text.Json;
public abstract partial class PageControllerBase : Microsoft.AspNetCore.Mvc.ControllerBase
public abstract partial class PageControllerBase : Microsoft.AspNetCore.Mvc.ControllerBase
{
private static readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver(), // PascalCase as default
};
private static readonly object _systemTextSerializerOptions = new JsonSerializerOptions();
protected Services Services => (Services) Request.HttpContext.Items[typeof(Services)];
protected string GetRouteData(string key) => RouteData.Values[key].ToString();
protected IActionResult Json( object content ) => new JsonResult( content, _serializerSettings );
protected IActionResult Json( object content )
{
var executor = HttpContext.RequestServices.GetRequiredService<IActionResultExecutor<JsonResult>>();
var serializerOptions = executor.GetType().FullName.Contains("SystemTextJson")
? _systemTextSerializerOptions
: _serializerSettings;
return new JsonResult(content, serializerOptions);
}
protected IActionResult NotModified() => new StatusCodeResult(304);

View File

@@ -3,9 +3,12 @@ namespace SilkierQuartz.Helpers
{
#if (NETSTANDARD || NETCOREAPP)
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Text.Json;
public class JsonErrorResponseAttribute : ActionFilterAttribute
{
@@ -13,12 +16,18 @@ namespace SilkierQuartz.Helpers
{
ContractResolver = new DefaultContractResolver(), // PascalCase as default
};
private static readonly object _systemTextSerializerOptions = new JsonSerializerOptions();
public override void OnActionExecuted(ActionExecutedContext context)
{
if (context.Exception != null)
{
context.Result = new JsonResult(new { ExceptionMessage = context.Exception.Message }, _serializerSettings) { StatusCode = 400 };
var executor = context.HttpContext.RequestServices.GetRequiredService<IActionResultExecutor<JsonResult>>();
var serializerOptions = executor.GetType().FullName.Contains("SystemTextJson")
? _systemTextSerializerOptions
: _serializerSettings;
context.Result = new JsonResult(new { ExceptionMessage = context.Exception.Message }, serializerOptions) { StatusCode = 400 };
context.ExceptionHandled = true;
}
}