【问题标题】:How to handle errors inside Custom JsonConverters in asp net core?如何处理asp net core中自定义JsonConverters中的错误?
【发布时间】: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


【解决方案1】:

要解决 Sunny 忽略“提供的值无效”消息的问题,您必须使用 throw JsonException 而不是 FormatException。

public override DateTime Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options)
{
    if (DateTime.TryParseExact(
    reader.GetString(),
    "dd-MM-yyyy hh:mm tt",
    CultureInfo.InvariantCulture,
    DateTimeStyles.None, 
    out DateTime date))
{
    return date;
}
    throw new JsonException("Property is not in a proper date format.");
}

【讨论】:

    【解决方案2】:

    在您的转换器中,您可以使用TryParse OR TryParseExact 方法并使用不同的错误消息自己抛出异常,而不是使用像DateTime.Parse 这样的API 来为无效格式的输入引发异常.我假设您仍然希望保持异常的类型相同(即FormatException)。

    public override DateTime Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options)
    {
        if (DateTime.TryParseExact(
            reader.GetString(),
            "dd-MM-yyyy hh:mm tt",
            CultureInfo.InvariantCulture,
            DateTimeStyles.None, 
            out DateTime date))
        {
            return date;
        }
        throw new FormatException("A DateTime property is not in a proper format.");
    }
    

    如果您希望在转换器中访问属性名称本身(放入异常消息或出于任何其他原因),这并不容易。如果您确实需要,实现此目的的一种方法是为您正在序列化的具有DateTime 属性的父类型创建一个转换器并以这种方式访问​​它。这种方法并不理想,特别是如果您碰巧在许多不同的父类型中有这样的 DateTime 属性(因为它需要您为所有这些类型创建自定义转换器)。不管怎样,这里有一个 sn-p 作为示例,它使用典型的 WeatherForecast 父类型,其中包含 DateTime 和 dotnet new webapi 模板:

    // The "Read" side of a JsonConverter<WeatherForecast> implementation
    
    public override WeatherForecast Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options)
    {
        var forecast = new WeatherForecast();
    
        while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)
        {
            if (reader.ValueTextEquals(nameof(forecast.Date)))
            {
                if (!reader.Read())
                {
                    throw new JsonException();
                }
    
                if (DateTime.TryParseExact(
                            reader.GetString(),
                            "dd-MM-yyyy hh:mm tt",
                            CultureInfo.InvariantCulture,
                            DateTimeStyles.None, 
                            out DateTime date))
                {
                    forecast.Date = date;
                }
                else
                {
                    throw new FormatException(
                        $"The {nameof(forecast.Date)} is not in a proper format.");
                }
            }
    
            // Add logic for creating the rest of the object properties from the JSON.
        }
    
        return forecast;
    }
    

    【讨论】:

    • 感谢您的回复。我尝试了使用 DateTime.TryParseExact() 并引发格式异常的第一个解决方案,但是由于我有一个用于检查模型状态错误的操作过滤器,因此它给出了相同的消息。 “提供的值无效”。为了更清楚,我已经编辑了我的问题
    猜你喜欢
    • 1970-01-01
    • 2010-09-27
    • 2019-10-01
    • 2017-11-16
    • 2022-08-17
    • 1970-01-01
    • 2023-01-05
    • 1970-01-01
    • 2019-10-19
    相关资源
    最近更新 更多