【问题标题】:How to allow Enum Description to be used in POST body如何允许在 POST 正文中使用枚举描述
【发布时间】:2021-09-08 03:25:51
【问题描述】:

我们希望允许用户在使用Description 属性发送 POST 请求时输入枚举的“友好”名称。

我们的一些枚举包含多个单词,所以基本上我们希望允许用户输入描述而不是实际的枚举名称。

例如我们有以下 Enum 类:

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

请求类:

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

以及以下请求负载:

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

随着有效负载的进入,我们希望将"MethodType": "Credit Card" 映射到PaymentMethodType.CreditCard。

关于如何实现这一点的任何建议?

【问题讨论】:

  • 你需要一个用于PaymentMethodType的JsonConverter。
  • 嘿@Llama,你能详细说明一下吗?在这种情况下我将如何使用 JsonConverter。
  • 检查了这个问题的大量答案? stackoverflow.com/questions/59059989/…

标签: c# asp.net-core asp.net-web-api enums


【解决方案1】:

试试这个:

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

为此,您需要安装“Newtonsoft.Json”包。您可以使用 Visual Studios NuGet Package UI 或使用 shell 进行编码:

dotnet add package Newtonsoft.Json

然后在你的课堂上使用它们:

using Newtonsoft.Json; //for JsonConverter
using Newtonsoft.Json.Converters; //for StringEnumConverter

【讨论】:

  • StringEnumConverter 使用EnumMemberAttribute,而不是DescriptionAttribute。
猜你喜欢
  • 1970-01-01
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
  • 2012-10-01
  • 2013-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多