Post 包含枚举描述的请求

Post Request that includes a Enum description

我正在 .net 核心中制作一个简单的 API,并试图实现一个 post,我需要在其中处理枚举值。

我为此使用了 "SaveProfileResource",AutoMapper 在我的控制器中使用了它 class。

我特别想要的是用这样的正文发出 post 请求:

{
    "FirstName": "Karl",
    "LastName": "Marx",
    "UserName": "MarxDidNothingWrong69",
    "Gender": "Diverse"
}

其中 Gender 是一个枚举。

代码看起来像这样:

public class SaveProfileResource
{
    [Required]
    [MaxLength(60)]
    public string FirstName { get; set; }

    [Required]
    [MaxLength(60)]
    public string LastName {get; set;}

    [Required]
    [MaxLength(60)]
    public string UserName {get; set;}

    [Required]
    public EGender Gender {get; set;}
}

EGender 看起来像这样:

public enum EGender
{
    [Description("Male")]
    Male = 1,

    [Description("Female")]
    Female = 2,

    [Description("Diverse")]
    Diverse = 3,
}

和我控制器中的 post 方法 class:

[HttpPost]
public async Task<IActionResult> PostAsync([FromBody] SaveProfileResource resource){
    if(!ModelState.IsValid){
        return BadRequest(ModelState.GetErrorMessages());
    }
    var profile = mapper.Map<SaveProfileResource, Profile>(resource);
    var result = await profileService.SaveAsync(profile);

    if(!result.Success){
        return BadRequest(result.Message);
    }
    var profileResource = mapper.Map<Profile, ProfileResource>(result.Profile); //displaying the result to the user

    return Ok(profileResource);
}

使用我当前的 "raw" 实现,我得到了

"The JSON value could not be converted to x.y.z.Models.EGender. Path: "

错误。我的问题是:

我需要做什么才能发送包含性别枚举描述的请求。

试试这个

[JsonConverter(typeof(StringEnumConverter))]
[Required]
public EGender Gender {get; set;}

为此,您需要安装 "Newtonsoft.Json" 软件包。 您可以使用 Visual Studios NuGet 包 UI 或者如果使用 shell:

进行编码

dotnet add package Newtonsoft.Json

然后在您的 class:

中使用它们
using Newtonsoft.Json; //for JsonConverter
using Newtonsoft.Json.Converters; //for StringEnumConverter

另一个解决方案是为此使用映射配置文件(不确定这里的术语是否正确)。

public class ResourceToModelProfile : Profile
{
    public ResourceToModelProfile()
    {
        CreateMap<SaveProfileResource, Profile>()
            .ForMember(src => src.Gender,
                       opt => opt.MapFrom(src => Enum.Parse(typeof(EGender), src.Gender)));
    }
}

工作起来很有魅力,除了我需要使用实际的变量名而不是描述(在这种情况下,因为两者匹配所以没有太大区别)