相关疑难解决方法(0)

枚举类型不再适用于 .Net core 3.0 FromBody 请求对象

我最近将我的 web api 从 .Net core 2.2 升级到 .Net core 3.0,并注意到当我将帖子中的枚举传递给我的端点时,我的请求现在出现错误。例如:

我的 api 端点有以下模型:

    public class SendFeedbackRequest
    {
        public FeedbackType Type { get; set; }
        public string Message { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

反馈类型如下所示:

    public enum FeedbackType
    {
        Comment,
        Question
    }
Run Code Online (Sandbox Code Playgroud)

这是控制器方法:

    [HttpPost]
    public async Task<IActionResult> SendFeedbackAsync([FromBody]SendFeedbackRequest request)
    {
        var response = await _feedbackService.SendFeedbackAsync(request);

        return Ok(response);
    }
Run Code Online (Sandbox Code Playgroud)

我将它作为帖子正文发送给控制器的地方:

{
    message: "Test"
    type: "comment"
}

Run Code Online (Sandbox Code Playgroud)

我现在收到以下错误发布到此端点:

The JSON value could not be converted to MyApp.Feedback.Enums.FeedbackType. Path: $.type | LineNumber: 0 | …

c# asp.net-core-webapi asp.net-core-3.0 .net-core-3.0

33
推荐指数
3
解决办法
1万
查看次数

枚举作为 ASP.NET Core WebAPI 中的必填字段

[Required]当 JSON 请求没有为枚举属性提供正确的值时,是否可以返回属性错误消息?

例如,我有一个包含AddressType枚举类型属性的 POST 消息模型:

public class AddressPostViewModel
{
    [JsonProperty("addressType")]
    [Required(ErrorMessage = "Address type is required.")]
    public AddressType AddressType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

AddressType枚举接受两个值:

[JsonConverter(typeof(StringEnumConverter))]
public enum AddressType
{
    [EnumMember(Value = "Dropship")]
    Dropship,
    [EnumMember(Value = "Shipping")]
    Shipping
}
Run Code Online (Sandbox Code Playgroud)

我注意到(或者实际上我的 QA 团队注意到)如果请求消息 JSON 包含空字符串或 null AddressType,则错误消息不是预期的Address type is required.消息。相反,错误消息是一个有点不友好的解析错误。

例如,如果请求 JSON 如下所示:

{  "addressType": "" }
Run Code Online (Sandbox Code Playgroud)

然后验证框架自动生成的错误如下所示:

{
    "message": "Validation Failed",
    "errors": [
        {
            "property": "addressType",
            "message": "Error converting value \"\" …
Run Code Online (Sandbox Code Playgroud)

c# enums asp.net-core-webapi

8
推荐指数
2
解决办法
1万
查看次数