【发布时间】:2020-07-01 06:52:13
【问题描述】:
我在我的 Web API 项目中使用了 net core 3.1。为了在 JSON 请求正文中接受用户的 dd-MM-yyyy 格式的日期,我创建了一个 DateTime 转换器,它将所有传入和传出的日期转换为指定的格式。
下面是我的日期时间转换器:
public class DateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Debug.Assert(typeToConvert == typeof(DateTime));
return DateTime.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString("dd-MM-yyyy hh:mm tt"));
}
}
我已经在 startup.cs 中注册了相同的内容,例如:
services.AddControllers(options =>
{
//To accept browser headers.
options.RespectBrowserAcceptHeader = true;
}).
AddNewtonsoftJson(options =>
{
// Use the default property (Pascal) casing
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
}).
AddJsonOptions(options =>
{
//converter to accept date in particular(dd-MM-yyyy) format
options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
});
现在我在 DateTime Converter 中遇到了某些问题。我创建了一个动作过滤器,用于检查从 DateTime 转换器引发异常后调用的 ModelState 错误。下面是 ModelState 错误过滤器:
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
ApiResponseModel<IEnumerable<ValidationErrorModel>> apiResponseModel = new ApiResponseModel<IEnumerable<ValidationErrorModel>>();
apiResponseModel.ResponseCode = (int)HttpStatusCode.BadRequest;
apiResponseModel.ResponseMessage = string.Join(" ",
context.ModelState.Values.Where(E => E.Errors.Count > 0)
.SelectMany(E => E.Errors)
.Select(E => E.ErrorMessage)
.ToArray());
apiResponseModel.ResponseData = null;
context.Result = new OkObjectResult(apiResponseModel);
}
}
当日期格式不正确时,例如在 MM-dd-YYYY 格式中,它会生成 ModelState 错误并将其内置错误消息显示为“提供的值无效”。我想显示一条不同的消息而不是这条内置消息,例如“{nameofdatetimefield} 的格式不正确。”。那么我怎样才能在这个 DateTimeConverter 中实现同样的效果呢?
【问题讨论】:
-
您要使用
Newtonsoft.Json还是System.Text.Json?你为什么要打电话给AddNewtonsoftJson以及与System.Text.Json一起使用的转换器?我会尽量避免混合 JSON 库。你的DateTimeConverter被叫到了吗? -
@ahsonkhan 。我使用了 Newtonsoft.Json,因为 System.Text.Json 中仍然不支持某些功能。是的 DateTimeConverter 被调用了。
标签: c# asp.net-core-webapi .net-core-3.1 system.text.json