0

I have an ASP.NET MVC 5.2.7 project (not Core)

public ActionResult Magic()
{
    MyType model = BuildModel();
    return View("Index", model);
}

[HttpPost]
public ActionResult Magic(MyType model)
{
}

public class MyType
{
    [JsonConverter(typeof(MyConverter<MySubType>))]
    public TySubType Value { get; set; }
}

[DataContract]
[JsonConverter(typeof(MyConverter<MySubType>))]
public enum MySubType
{
    [EnumMember("v1")]
    MyV1
}

public class MyConverter<T> : JsonConverter
    where T: Enum
{
    public override bool CanConvert(Type objectType) => objectType is T;
    public override bool CanRead => true;
    public override bool CanWrite => true;

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {}

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {}
}

With this configuration, my WriteJson is called on GET, but not used on POST to deserialize the body. What should be changed here?

In the end, I'm trying to get it using the EnumMember value to serialize/deserialize enums

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
dr11
  • 5,166
  • 11
  • 35
  • 77
  • Json.NET's [`StringEnumConverter`](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Converters_StringEnumConverter.htm) already suppports `EnumMemberAttribute`, and has done so since [Json.NET 4.0 Release 2](http://james.newtonking.com/archive/2011/04/21/json-net-4-0-release-2-nuget-1-2-and-dynamic). If that is what you want, why are you creating your own converter? – dbc Oct 05 '22 at 17:21
  • 1
    Might you please [edit] your question to share a [mcve], specifically the raw POST including the headers and body? Is there a chance you are posting your values in the query string rather than the request body? – dbc Oct 05 '22 at 17:22
  • @dbc you're right, I use JSON encoder to pass it to the page, but the data is submitted as a Form url-encoded data and it does not go thru my logic. is that possible to deserialize form data with my converter? – dr11 Oct 05 '22 at 18:46
  • A `JsonConverter` and Json.NET in general are only designed to deserialize JSON -- a *lightweight, text-based, language-independent data interchange format* defined by [rfc8259](https://www.rfc-editor.org/rfc/rfc8259). You can't use them to deserialize anything other than data in the support formats. (BSON is also supported). For URL parameter binding you need a custom model binder or type converter. – dbc Oct 05 '22 at 19:25
  • See: [Deserialize enums using the EnumMember value in AspNet `[FromQuery]` model binding](https://stackoverflow.com/q/72886747/3744182). In fact that may be a duplicate despite being asked about .NET Core; agree? – dbc Oct 05 '22 at 19:25

0 Answers0