【问题标题】:How I can set JSON serialization rules for validation messages?如何为验证消息设置 JSON 序列化规则?
【发布时间】:2020-02-19 21:00:02
【问题描述】:

我的Startup.cs 中有以下 JSON 策略配置:

services.AddControllers().ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        // options.SuppressMapClientErrors = true;
    }) 
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy =
            SnakeCaseNamingPolicy.Instance;
    });

和政策:

public class SnakeCaseNamingPolicy : JsonNamingPolicy
{
    public static SnakeCaseNamingPolicy Instance { get; } = new SnakeCaseNamingPolicy();

    public override string ConvertName(string name)
    {
        // Conversion to other naming conventaion goes here. Like SnakeCase, KebabCase etc.
        return name.ToSnakeCase();
    }
}

还有ToSnakeCase

public static class StringUtils
{
    public static string ToSnakeCase(this string str)
    {
        return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() 
            : x.ToString())).ToLower();
    }
}

我用它来获取snake_case 中的 JSON。

这是我的模型:

public class CategoryViewModelCreate
{
    [Required(ErrorMessage = "Inner id is required")]
    [JsonPropertyName("inner_id")]
    public int? InnerId { get; set; }

    [Required(ErrorMessage = "Name is required")]
    [JsonPropertyName("name")]
    public string Name { get; set; }
}

我的控制器是:

public async Task<IActionResult> Create([FromBody] CategoryViewModelCreate viewModel)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

如果我有以下 JSON,现在它可以正常工作:

{
    "name": "testing",
    "inner_id": 123
}

但如果我的 JSON 是(没有名字):

{
    "inner_id": 123
}

我有以下验证消息:

{
  "Name": [
    "Name is required"
  ]
}

但这是错误的。我想要(name 而不是 Namesnake_case 其他键):

{
  "name": [
    "Name is required"
  ]
}

如何设置?在哪里?如您所见,我正在尝试使用[JsonPropertyName("name")], 但没有任何成功(

感谢您的帮助。

【问题讨论】:

    标签: c# json validation asp.net-core-webapi .net-core-3.1


    【解决方案1】:

    您可以创建您的基本继承控制器和 ovveride BadRequest(ModelStateDictionary m) 方法

    BadRequest(ModelStateDictionary model)
    {
        var newModel = model.ToDictionary(
                x => x.Key.ToCamelCase(),  
                x => kvp.Value
            );
        base.BadRequest(newModel);
    }
    

    类似的东西

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      相关资源
      最近更新 更多