ASP.NET Core WebAPI 模型验证 验证特性自定义返回

通过引用系统类库System.ComponentModel.DataAnnotations,实现模型的数据校验。

更多模型验证属性官方说明:https://docs.microsoft.com/zh-cn/dotnet/api/system.componentmodel.dataannotations?view=net-5.0

public class DemoModel
    {
        /// <summary>
        /// 主键
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// 姓名
        /// </summary>
        [Required(ErrorMessage = "姓名不能为空")]
        [StringLength(50, ErrorMessage = "姓名限制50个字符")]
        public string Name { get; set; }

        /// <summary>
        /// 年龄
        /// </summary>
        [Required(ErrorMessage = "年龄不能为空")]
        [Range(10, 80,ErrorMessage = "年龄字段限制范围 {1} - {2}")]
        public string Age { get; set; }

        /// <summary>
        /// 性别
        /// </summary>
        [Required(ErrorMessage = "性别不能为空")]
        public string Gender { get; set; }
    }

Demo控制器接口:

/// <summary>
/// 保存Demo数据
/// </summary>
[HttpPost]
[Route("save"), MapToApiVersion("1.0")]
public async Task<IActionResult> SaveDemo_V1_0([FromBody] DemoModel model)
{
    var result = await _mediator.Send(new SaveDemoCommand(model));
    result.apiVersion = HttpContext.GetRequestedApiVersion().ToString();//获取API版本号
    return Ok(result);
}

 

postman调用请求:

 此时发现返回的数据格式需要调整为自定义的统一格式,需要在Startup文件中做修改:

     // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            //模型绑定 特性验证,自定义返回格式
            services.Configure<ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    //获取验证失败的模型字段 
                    var errors = actionContext.ModelState
                    .Where(e => e.Value.Errors.Count > 0)
                    .Select(e => e.Value.Errors.First().ErrorMessage)
                    .ToList();
                    var strErrorMsg = string.Join("|", errors);
                    //设置返回内容
                    var result = new CommandResult<string>
                    {
                        success = false,
                        message = strErrorMsg
                    };
                    return new BadRequestObjectResult(result);
                };
            });
        }

CommandResult类:

public class CommandResult<T>
    {
        public CommandResult();

        public bool success { get; set; }
        public string message { get; set; }
        public string errCode { get; set; }
        public int resCode { get; set; }
        public string apiVersion { get; set; }
        public int timestamp { get; set; }
        public T data { get; set; }
    }

调整好消息返回格式后再次postman调用:

 此时发现返回的消息已经变成自定义的格式,问题得到解决。

参考文章:https://blog.csdn.net/joe96/article/details/93539675

 

posted @ 2020-12-21 12:40  Jackie Hao  阅读(1098)  评论(0编辑  收藏  举报