gpt4 book ai didi

c# - StringEnumConverter 无效的 int 值

转载 作者:行者123 更新时间:2023-11-30 14:26:22 27 4
gpt4 key购买 nike

我有一个带有 POST 方法的简单 Controller 。
我的模型有一个枚举类型的属性。
当我发送有效值时,一切都按预期进行

{  "MyProperty": "Option2"}

{  "MyProperty": 2}

如果我发送了一个无效的字符串

{  "MyProperty": "Option15"}

它正确获取默认值(Option1)但如果我发送一个无效的 int,它会保留无效值

{  "MyProperty": 15}

enter image description here

我能否避免这种情况并获取默认值或引发错误?

谢谢

public class ValuesController : ApiController
{
[HttpPost]
public void Post(MyModel value) {}
}

public class MyModel
{
[JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
public MyEnum MyProperty { get; set; }
}

public enum MyEnum
{
Option1 = 0,
Option2,
Option3
}

更新
我知道我可以将任何 int 转换为枚举,这不是问题。
@AakashM 的建议解决了我一半的问题,我不知道 AllowIntegerValues

现在我在发布一个无效的 int 时正确地得到了一个错误

{  "MyProperty": 15} 

现在唯一有问题的情况是当我发布一个数字字符串时(这很奇怪,因为当我发送一个无效的非数字字符串时它正确地失败了)

{  "MyProperty": "15"}

最佳答案

我通过扩展 StringEnumConverter 并使用@AakashM 的建议解决了我的问题

public class OnlyStringEnumConverter : StringEnumConverter
{
public OnlyStringEnumConverter()
{
AllowIntegerValues = false;
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (!AllowIntegerValues && reader.TokenType == JsonToken.String)
{
string s = reader.Value.ToString().Trim();
if (!String.IsNullOrEmpty(s))
{
if (char.IsDigit(s[0]) || s[0] == '-' || s[0] == '+')
{
string message = String.Format(CultureInfo.InvariantCulture, "Value '{0}' is not allowed for enum '{1}'.", s, objectType.FullName);
string formattedMessage = FormatMessage(reader as IJsonLineInfo, reader.Path, message);
throw new JsonSerializationException(formattedMessage);
}
}
}
return base.ReadJson(reader, objectType, existingValue, serializer);
}

// Copy of internal method in NewtonSoft.Json.JsonPosition, to get the same formatting as a standard JsonSerializationException
private static string FormatMessage(IJsonLineInfo lineInfo, string path, string message)
{
if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal))
{
message = message.Trim();
if (!message.EndsWith("."))
{
message += ".";
}
message += " ";
}
message += String.Format(CultureInfo.InvariantCulture, "Path '{0}'", path);
if (lineInfo != null && lineInfo.HasLineInfo())
{
message += String.Format(CultureInfo.InvariantCulture, ", line {0}, position {1}", lineInfo.LineNumber, lineInfo.LinePosition);
}
message += ".";
return message;
}

}

关于c# - StringEnumConverter 无效的 int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35479669/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com