Change default format for DateTime parsing in ASP.NET Core

前端 未结 10 1032
情话喂你
情话喂你 2021-02-02 08:57

I get a Date in an ASP.NET Core Controller like this:

public class MyController:Controller{
    public IActionResult Test(DateTime date) {

    }
}
10条回答
  •  一整个雨季
    2021-02-02 09:58

    If you don't mind using the generic StatusCode method to make this call, you can do something like the following:

    internal IActionResult CreateResponse(int code, object content = null)
        {
            Type t = content?.GetType();
            bool textContent = t == typeof(string) || t == typeof(bool);
            //
            JsonSerializerSettings dateFormatSettings = new JsonSerializerSettings
            {
    
                DateFormatString = myDateFormat
            };
    
            string bodyContent = content == null || string.IsNullOrWhiteSpace(content + "")
                        ? null
                        : textContent
                            ? content + ""
                            : JsonConvert.SerializeObject(content, dateFormatSettings);
    
            ObjectResult or = base.StatusCode(code, bodyContent);
            string mediaType = 
                        !textContent
                            ? "application/json"
                            : "text/plain";
            or.ContentTypes.Add(new MediaTypeHeaderValue(mediaType));
            return or;
        }
    

    You can add this to a base class and call it like:

    return base.CreateResponse(StatusCodes.Status200OK, new { name = "My Name", age = 23});
    

    It's up to you if you want to create your own Ok, BadRequest, etc...methods, but for me this works and I hope it helps anybody else. You could even default int code = 200, if most of your requests are GETs. This code assumes you either want to respond with a string, boolean, or a custom object, but you can easily handle all primitives by checking Type.GetTypeInfo().IsPrimitive and even doing some checks for decimal, string, DateTime, TimeSpan, DateTimeOffset, or Guid.

提交回复
热议问题