.net core 3.x webapi的输入验证和自定义错误

记录一下自己在.net core 3.0中使用webapi的一些输入验证

 

  1. 输入验证

1.1  Data Annotations

在使用post/put/patch等请求过程中,api通常会接收model类型参数,可以使用DataAnnotations特性来约束一般参数,在需要验证的参数上直接加上注解,如下:

   [Display(Name = "名字")]
   [Required(ErrorMessage = "{0}是必须的")]
   public string Name { get; set; }

1.2 IValidatableObject

被当作api接收参数类型的model需要实现IValidatableObject接口的 Validate方法,如下:

 public IEnumerable Validate(ValidationContext validationContext)
        {
            if (Name == Add)
            {
                yield return new ValidationResult("姓名和地址不能一样", new[] { nameof(DemoDto) });
            }
        }

1.3 自定义Attribute

 自己新建一个类,并且继续类ValidationAttribute然后重写类里面的IsValid方法,如下:

public class DemoDifferenceAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var demodto = (DemoDto)validationContext.ObjectInstance;
            if (demodto.Name == demodto.Add)
            {
                return new ValidationResult(ErrorMessage, new[] { nameof(DemoDto) });
            }
            return ValidationResult.Success;
        }
    }

 

  1. 自定义错误

自定义错误信息需要在Startup.cs类里进行依赖注入,在services.AddControllers等后面,如下:

 

 services.AddControllers(setup=> {
                setup.ReturnHttpNotAcceptable = true;
                setup.CacheProfiles.Add("120CacheProfile", new CacheProfile()
                {
                    Duration = 120
                });
            }).AddXmlDataContractSerializerFormatters()
            .ConfigureApiBehaviorOptions(setup=> 
            {
                setup.InvalidModelStateResponseFactory = context => {
                    var problemdetails = new ValidationProblemDetails(context.ModelState)
                    {
                        Type = "http://localhost:8082", //自己定义
                        Title = "有错误",
                        Status = StatusCodes.Status422UnprocessableEntity,
                        Detail = "请看详细信息",  //自己定义
                        Instance = context.HttpContext.Request.Path
                    };
                    problemdetails.Extensions.Add("traceId", context.HttpContext.TraceIdentifier);

                    return new UnprocessableEntityObjectResult(problemdetails)
                    {
                        ContentTypes = { "application/problem+json" }
                    };
                };
            });

 

你可能感兴趣的:(.Net,Core)