ASP.NET Core 8 Web API 数据验证忽略数据注释

问题描述 投票:0回答:1

我正在尝试在

ApiController
中进行自动数据验证,但是当用户发送不正确/丢失的数据时,会返回 JSON 反序列化失败错误消息,而不是自定义
ErrorMessage

ProfilesController.cs

using ClassLibrary.Models;
using ClassLibrary.Services;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using ClassLibrary.Models.API.Responses.Profiles;
using ClassLibrary.Models.API.Requests;
using Microsoft.AspNetCore.Authorization;

namespace API.Controllers
{
    [ApiController]
    [Route("v1/[controller]")]
    public class ProfilesController : Controller
    {
        private IProfileManager _profileManager;

        public ProfilesController(IProfileManager profileManager)
        {
            _profileManager = profileManager;
        }

        [Authorize]
        [HttpPatch("about")]
        public async Task<IActionResult> UpdateAbout([FromBody] UpdateAboutPayload payload)
        {
            await _profileManager.UpdateAboutAsync(payload.About);

            return Ok();
        }
    }
}

更新AboutPayload.cs

using System.ComponentModel.DataAnnotations;

namespace ClassLibrary.Models.API.Requests
{
    public class UpdateAboutPayload
    {
        [Required(ErrorMessage = "About is required")]
        [StringLength(500, ErrorMessage = "About must be between 0 and 500 characters long")]
        public required string About { get; set; }
    }
}

当我发送以下数据时

{}

我收到此错误

{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "$": [
      "JSON deserialization for type 'ClassLibrary.Models.API.Requests.UpdateAboutPayload' was missing required properties, including the following: about"
    ],
    "payload": [
      "The payload field is required."
    ]
  },
  "traceId": "00-402c938fa2cb172de6a89b521f8fcae1-88ebfe9d6c674e35-00"
}

而不是在

[Required]
属性中配置的错误消息

c# asp.net-core validation asp.net-core-webapi data-annotations
1个回答
0
投票

这是正确的行为,您没有发送整个对象,因此您会收到需要有效负载字段的异常,如果您只想“需要关于”消息,则需要发送空白有效负载,如下所示

{ 
   payload: {} 
}
© www.soinside.com 2019 - 2024. All rights reserved.