简体   繁体   中英

JsonConverter attribute on enum breaks asp.net core model binding

I have a simple class which contains an Enum as a property:

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:

public async Task<JsonResult> Post([FromBody] MyClass myClass)
{
 //Some exciting controllery type stuff in here....
}

And posting data from 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:

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. So after a bit of Googling I decorate the enum attribute with

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM