如何为验证消息设置JSON序列化规则?

问题描述 投票:0回答:1

我在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个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.