ASP.NET Core Web API 验证错误处理

Ben*_*Ben 5 c# validation asp.net-web-api asp.net-core-mvc asp.net-core

当模型在我的 Web API 项目中验证失败时,我试图返回自定义响应对象。我已将属性附加到模型中,如下所示:

  public class DateLessThanAttribute : ValidationAttribute
  {
    private readonly string _comparisonProperty;

    public DateLessThanAttribute(string comparisonProperty)
    {
      _comparisonProperty = comparisonProperty;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
      ErrorMessage = ErrorMessageString;
      var currentValue = (DateTime)value;

      var property = validationContext.ObjectType.GetProperty(_comparisonProperty);

      if (property == null)
        throw new ArgumentException("Property with this name not found");

      var comparisonValue = (DateTime)property.GetValue(validationContext.ObjectInstance);

      if (currentValue > comparisonValue)
        return new ValidationResult(ErrorMessage);

      return ValidationResult.Success;
    }
  }
Run Code Online (Sandbox Code Playgroud)

在模型上:

[DateLessThan("EndDate", ErrorMessage = "StartDate must be less than EndDate")]
public DateTime StartDate { get; set; }
Run Code Online (Sandbox Code Playgroud)

和控制器:

public void PostCostingStandard(CostStandardRequest request)
{
  CostResult costResult;
  if (ModelState.IsValid)
  {
    // work
  }
  else
  {
    // return bad costResult object
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,模型永远不会到达控制器内部以点击ModelState.IsValid。我已经尝试创建一个ActionFilterAttribute并将其附加到我的控制器操作中,如here所述,但是在设置断点时,它ActionFilterAttribute永远不会运行,因为 DateLessThanAttribute 首先返回响应。这些过滤器是否有我遗漏的命令,或者我只是错误地实现了某些东西?

Dan*_*jel 7

您必须禁用自动模型状态验证。您可以通过将以下代码添加到您的startup.cs 来实现

services.Configure<ApiBehaviorOptions>(options =>
{
    options.SuppressModelStateInvalidFilter = true;
});
Run Code Online (Sandbox Code Playgroud)