0

We want to allow users to enter the "friendly" name of an Enum when sending a POST request using the Description attribute.

Some of our Enums contain multiple words so basically we want to allow the user to enter the Description rather than the actual Enum name.

For example we have the following Enum class:

public enum PaymentMethodType
{
    [Description("Other")]
    Other = 0,
    [Description("Cash")] 
    Cash = 1,
    [Description("Credit Card")] 
    CreditCard = 2,
    [Description("Debit Card")] 
    DebitCard = 3
}

Request Class:

public class TransactionPaymentDetailRequest
{
    public PaymentMethodType? MethodType { get; set; }
}

And the following request payload:

{
    "TransactionPaymentDetails": [
        {
           "MethodType": "Credit Card"
        }
    ]
}

As the payload comes in we would like "MethodType": "Credit Card" to be mapped to PaymentMethodType.CreditCard.

Any suggestions on how to achieve this?

M0rty
  • 985
  • 3
  • 15
  • 35

1 Answers1

0

Try this:

[JsonConverter(typeof(StringEnumConverter))]
[Required]
public PaymentMethodType? MethodType { get; set; }

for this you need to install the "Newtonsoft.Json" package. You can do that using Visual Studios NuGet Package UI or if coding using shell:

dotnet add package Newtonsoft.Json

and then using them in your class:

using Newtonsoft.Json; //for JsonConverter
using Newtonsoft.Json.Converters; //for StringEnumConverter
Tupac
  • 2,590
  • 2
  • 6
  • 19