[英]JsonConverter attribute on enum breaks asp.net core model binding
I have a simple class which contains an Enum as a property: 我有一个简单的类,其中包含一个Enum作为属性:
public class MyClass
{
public MyEnum Type { get; set; }
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
public enum MyEnum
{
Something,
OrOther
}
I'm then using this in asp.net web api to model bind: 然后我在asp.net web api中使用它来建模bind:
public async Task<JsonResult> Post([FromBody] MyClass myClass)
{
//Some exciting controllery type stuff in here....
}
And posting data from Fiddler: 并从Fiddler发布数据:
{
"Type":"0",
"Prop1":"TestValue",
"Prop2":"MoreTestData"
}
And all is working well. 一切都运作良好。 Now I want to post to this API from inside a Xamarin application, so use:
现在我想从Xamarin应用程序内部发布到这个API,所以使用:
var stringData = JsonConvert.SerializeObject(data);
where data is an instance of MyClass but the enum is getting converted to an integer, not its string value. 其中data是MyClass的一个实例,但枚举转换为整数,而不是其字符串值。 So after a bit of Googling I decorate the enum attribute with
所以经过一些谷歌搜索后,我用它来装饰enum属性
public class MyClass
{
[JsonConverter(typeof(StringEnumConverter))]
public MyEnum Type { get; set; }
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
And now my serialization is working correctly and the value is coming through as the string representation of the enum, not the integer value. 现在我的序列化工作正常,值作为枚举的字符串表示形式,而不是整数值。
However, when I post from Fiddler now, using either the string or the integer, the model binding fails and the value is null. 但是,当我现在从Fiddler发布时,使用字符串或整数,模型绑定失败,值为null。
Is there a way to fix this so that both scenarios will work? 有没有办法解决这个问题,以便两种方案都有效?
Thanks 谢谢
You should add the serialization attribute to your enum definition as well 您还应该将序列化属性添加到枚举定义中
[JsonConverter(typeof(StringEnumConverter))]
public enum MyEnum
{
Something,
OrOther
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.