asp.net - 在 .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 值。
有没有其他实用的方法来限制字符串的选项而不使用枚举?或者有什么我可以使用枚举添加到这个解决方案中的吗?
非常感谢您的关注和时间!
解决方案
根据您的描述,我建议您可以为 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
}
结果:
推荐阅读
- python - 尝试使用 Python lib 下载图像,但没有任何反应,也没有出现任何错误
- solr - 如果用于搜索的最少 1 或 2 个字符,Alfresco SOLR4 通配符搜索不起作用
- sas - SAS Proc Freq 不显示值
- python - Keras:检查输入时出错:预期 input_1 的形状为 (299, 299, 3) 但数组的形状为 (229, 229, 3)
- mqtt - 导入 python 模块并访问 MQTT 端口
- java - Spring Boot JPA没有使用findById返回现有结果
- javascript - TypeError:this.state.map 不是函数
- sql - 数据库中属性的最佳数据类型是什么?整数还是字符?
- three.js - 三.js在场景左右移动相机
- c++ - 是什么导致这个有符号整数到无符号整数转换使用三元而不是短裤?