Skip to content

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

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 格式,并格式化日期


Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.