irc-netcore-api/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/CustomJsonResult .cs

126 lines
3.7 KiB
C#

using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Globalization;
using System.Threading.Tasks;
namespace IRaCIS.Core.API._ServiceExtensions.NewtonsoftJson
{
public class CustomJsonResult : JsonResult
{
public CustomJsonResult(object value) : base(value) { }
public override void ExecuteResult(ActionContext context)
{
var converter = context.HttpContext.RequestServices.GetService<JSONTimeZoneConverter>();
var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;
string dateFormat;
if (!isEn_US)
{
// Chinese date format
dateFormat = "yyyy-MM-dd HH:mm:ss";
}
else
{
// Default or English date format
dateFormat = "MM/dd/yyyy HH:mm:ss";
}
var serializerSettings = new JsonSerializerSettings
{
DateFormatString = dateFormat,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = new NullToEmptyStringResolver(),
DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind,
};
serializerSettings.Converters.Add(converter);
var json = JsonConvert.SerializeObject(Value, serializerSettings);
context.HttpContext.Response.ContentType = "application/json";
context.HttpContext.Response.WriteAsync(json);
}
}
public class MyDateTimeConverter : JsonConverter<DateTime>
{
public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer)
{
return reader.ReadAsDateTime().Value;
}
public override void WriteJson(JsonWriter writer, DateTime value, JsonSerializer serializer)
{
var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;
string dateFormat;
if (!isEn_US)
{
// Chinese date format
dateFormat = "yyyy-MM-dd HH:mm:ss";
}
else
{
// Default or English date format
dateFormat = "MM/dd/yyyy HH:mm:ss";
}
writer.WriteValue(value.ToString(dateFormat));
}
}
public class MyNullableDateTimeConverter : JsonConverter<DateTime?>
{
public override DateTime? ReadJson(JsonReader reader, Type objectType, DateTime? existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var val = reader.ReadAsDateTime();
return val;
}
public override void WriteJson(JsonWriter writer, DateTime? value, JsonSerializer serializer)
{
var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;
string dateFormat;
if (!isEn_US)
{
// Chinese date format
dateFormat = "yyyy-MM-dd HH:mm:ss";
}
else
{
// Default or English date format
dateFormat = "MM/dd/yyyy HH:mm:ss";
}
if (value.HasValue)
{
writer.WriteValue(value.Value.ToString(dateFormat));
}
else
{
writer.WriteValue(default(DateTime?));
}
}
}
}