微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

邮递员响应中未显示数据注释错误消息

如何解决邮递员响应中未显示数据注释错误消息

我有 web api 3.0 解决方案,但我没有任何 UI。我的所有回复都只在邮递员那里查过。 对于输入验证,我使用了数据注释,但我在 post man 中看不到错误消息。请帮助我我犯了什么错误

目前我收到如下错误信息:

{
"studentid": [
"Error converting value {null} to type 'system.int32'. Path 'studentid',line 2,position 26."
 ]
 }

但我想显示如下错误信息:

    student Id is required.This cannot be null or blank


    //[required (ErrorMessage = "student Id is required.This cannot be null or blank")]
     //public int StudentId { get; set; }

到目前为止我做了什么:

  1. 我的模型

    public class Employee
    {
     [required (ErrorMessage = "student Id is required.This cannot be null or blank")]
      public int StudentId { get; set; }
      [required (ErrorMessage = "Student name is required.This cannot be null or blank")]
       [StringLength(100,MinimumLength = 2)]
        public string FirstName { get; set; }
         [required]
        public string LastName { get; set; }
         [required (ErrorMessage = "Student age is required.This cannot be null or blank")]
          public int Age{ get; set; }
            }
    
  2. 我的控制器

       [HttpPost("api/Student/Check")]
        public async Task Check([FromBody] students input)
        {
       if (!ModelState.IsValid)
         {
        returnBadRequest(Modelstate);
           }
         else {
        returnOk();
        }
         }
    
  3. 为 ValidatorActionFilter.cs 创建了一个

     public class ValidatorActionFilter : IActionFilter
     {
       public void OnActionExecuting(ActionExecutingContext filterContext)
       {
       if (!filterContext.ModelState.IsValid)
          {
          filterContext.Result = new BadRequestObjectResult(filterContext.ModelState);
          }
          }
             public void OnActionExecuted(ActionExecutedContext filterContext)
            {
            }
             }
    

startup.cs

              public void ConfigureServices(IServiceCollection services)
           {
          services.AddMvc(options =>
          {
            options.Filters.Add(typeof(ValidatorActionFilter));
           });
           }

解决方法

您收到的邮递员错误是正确的。

默认情况下,int 数据类型不是 nullable,因此如果您将 null 分配给 int,则会出现错误。 您的 API 正在按预期工作,没有人应该将 nullstring 传递给 int 数据类型,但是如果您希望 StudentId 使用 null 那就让它nullable,像这样:

public class Employee
    {
      [Required (ErrorMessage = "student Id is required.This cannot be null or blank")]
      public int? StudentId { get; set; }
      //rest of your properties
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。