Skip to content

WebAPI 自定义返回的 JSON 日期格式

🏷️ .NET Core

1. 在 Application_Start 中添加方法调用

csharp
// 自定义 json 格式
ConfigureApi(GlobalConfiguration.Configuration);

2. 自定义日期格式方法

csharp
/// <summary>
/// 自定义 json 格式
/// </summary>
/// <param name="config"></param>
public static void ConfigureApi(HttpConfiguration config)
{
    var jsonFormatter = new JsonMediaTypeFormatter();
    var settings = jsonFormatter.SerializerSettings;

    IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
    //这里使用自定义日期格式
    timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
    settings.Converters.Add(timeConverter);

    //settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
}

3. 自定义 JsonContentNegotiator

csharp
public class JsonContentNegotiator : IContentNegotiator
{
    private readonly JsonMediaTypeFormatter _jsonFormatter;

    public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
    {
        _jsonFormatter = formatter;
    }

    public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
    {
        var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
        return result;
    }
}

原文:WebApi 返回小驼峰式 json 格式,并格式化日期