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

标签 c# validation asp.net-web-api asp.net-core asp.net-core-mvc

当模型在我的 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;
    }
  }

在模型上:

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

和 Controller :

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

但是,模型永远不会到达 Controller 内部以命中 ModelState.IsValid。我已经尝试创建一个 ActionFilterAttribute 并将其作为 outlined here 附加到我的 Controller 操作中,但是在设置断点时,ActionFilterAttribute 永远不会运行,因为 DateLessThanAttribute 首先返回响应。是否有我错过的这些过滤器的顺序,或者我只是错误地实现了什么?

最佳答案

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

来实现
services.Configure<ApiBehaviorOptions>(options =>
{
    options.SuppressModelStateInvalidFilter = true;
});

关于c# - ASP.NET Core Web API 验证错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53177081/

相关文章:

c# - 打印文档

php - 如何在 Laravel 中使用正则表达式验证来验证年份?

c# - 带有特殊字符的 ASP.NET MVC 身份电子邮件/用户名

asp.net OAuth token 错误 401 : unauthorized

c# - 列表框未使用绑定(bind)填充

c# - 如何使用2*Xeon E5的电源?

c# - C# 中使用 lambda 和匿名方法的闭包

java - Spring MVC : What's the right way to register custom Validator in REST controller

validation - 对铁路模型进行验证

c# - .NET core Web API,如何更改使用 IAsyncEnumerable 时返回的 XML 的根名称?