首页 > 解决方案 > 在 .NET Core WebAPI 3.1 中使用受限字符串字段值

问题描述

我正在使用.netcore开发一个webapi项目。

我有一个具有以下属性的模型:

public class Criterial {
  [Required]
  public string Field { get; set; }

  [Required]
  public Operator Operator { get; set; }

  [Required]
  public string Value { get; set; }

  public bool Result { get; set; }
}

public enum Operator {
    greater_than,
    equal_to,
    lower_than
}

我正在尝试使用枚举来限制Operator属性可以接收的值,但是当我向 API 发出 POST 请求时,我得到了以下情况:

POST 请求正文:

"criterials": [
    {
        "field": "amount",
        "operator": "greater_than",
        "value": "50"
    }
]

来自 API 的响应:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|7e53377-444fa4a723ac655c.",
    "errors": {
        "$.criterials[0].operator": [
            "The JSON value could not be converted to LeagueOfFateApi.Models.Operator. Path: $.criterials[0].operator | LineNumber: 5 | BytePositionInLine: 26."
        ]
    }
}

在互联网上搜索该问题,我发现了[JsonConverter(typeof(JsonStringEnumConverter))]数据注释。

所以我将它添加到我的代码中,问题得到了“解决”:

[Required]
[JsonConverter(typeof(JsonStringEnumConverter))]
public Operator Operator { get; set; }

来自 API 的新响应:

"criterials": [
    {
        "field": "amount",
        "operator": "greater_than",
        "value": "50",
        "result": false
    }
]

问题是:在我的MongoDB集合中,使用枚举的int 值 0保存了一个新文档,而不是字符串值 "greater_than"

"Criterials" : [
    {
        "Field" : "amount",
        "Operator" : 0,
        "Value" : "50",
        "Result" : false
    }
]

此外,另一个问题是“criterial”字段可以不受限制地接收任何 int 值。

有没有其他实用的方法来限制字符串的选项而不使用枚举?或者有什么我可以使用枚举添加到这个解决方案中的吗?

非常感谢您的关注和时间!

标签: asp.net.netasp.net-coreasp.net-web-apienums

解决方案


根据您的描述,我建议您可以为 Operator 属性编写自定义 set 和 get 方法。

您可以将运算符的类型设置为字符串并用于Enum.IsDefined检查Operator值是否 enum Operator

更多细节,您可以参考以下代码:

public class Criterial
{
    [Required]
    public string Field { get; set; }

    private string _Operator;

    [Required]
    public string Operator {
        get {
            return this._Operator;
        }
        set {
            if (Enum.IsDefined(typeof(Operator), value))
            {
                this._Operator = value;
            }
            else
            {
                this._Operator = "Error you used wrong string";
            }
        } 
    
    }

    [Required]
    public string Value { get; set; }

    public bool Result { get; set; }
}

public enum Operator
{
    greater_than,
    equal_to,
    lower_than
}

结果:

在此处输入图像描述


推荐阅读