简体   繁体   English

我需要在 ASP.Net 核心的验证属性中返回自定义验证结果(响应) Web API

[英]I need to return customized validation result (response) in validation attributes in ASP.Net core Web API

I need to return customized validation result (response) invalidation attributes in ASP.Net core Web API This is the ValidationAttribute I have created.我需要在 ASP.Net core 中返回自定义的验证结果(响应)失效属性 Web API 这是我创建的 ValidationAttribute。

class MaxResultsAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        int maxResults = (int)value;

        if (maxResults <= 0)
        {
            return new CustomValidationResult(new ValidationResult("MaxResults should be greater than 0"));
        }

        return ValidationResult.Success;
    }
}

I have created CustomValidationResult object inheriting ValidationResult so that I can return my own customized response:我创建了继承 ValidationResult 的 CustomValidationResult object 以便我可以返回我自己的自定义响应:

public class CustomValidationResult : ValidationResult
{
    public int FaultCode { get; set; }

    public string FaultMessage { get; set; }

    public CustomValidationResult(ValidationResult validationResult) : base(validationResult)
    {
        FaultCode = 123;
        FaultMessage = validationResult.ErrorMessage;
    }
}

But it's not working I need to return my own error response但它不起作用我需要返回我自己的错误响应

Actual Response:实际响应:

    {
      "MaxResults": [
        "MaxResults should be greater than 0"
      ] 
    }

The response I'm expecting:我期待的回应:

    {
      "code": "55",
      "message": "The following validation errors occurred: MaxResults should be greater than 0"
    }

The response I'm expecting:我期待的回应:

 { "code": "55", "message": "The following validation errors occurred: MaxResults should be greater than 0" }

I have reproduced the problem using your code, using the CustomValidationResult, I could only get the Actual Response like yours.我已经使用你的代码重现了这个问题,使用 CustomValidationResult,我只能得到像你这样的实际响应。 To achieve above behavior, as a workaround, I suggest you could try to use the action filter to handle the Validation failure error response.要实现上述行为,作为解决方法,我建议您可以尝试使用操作过滤器来处理验证失败错误响应。 Check the following sample code:检查以下示例代码:

  1. Create custom ValidationError model which contains the returned fields:创建包含返回字段的自定义 ValidationError model:

     public class ValidationError { [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string Field { get; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public int Code { get; set; } public string Message { get; } public ValidationError(string field,int code, string message) { Field = field.= string?Empty: field; null? Code = code:= 0; code; 55; Message = message; } } public class ValidationResultModel { public string Message { get; } public List<ValidationError> Errors { get. } public ValidationResultModel(ModelStateDictionary modelState) { Message = "Validation Failed". Errors = modelState.Keys.SelectMany(key => modelState[key],Errors,Select(x => new ValidationError(key.0. x;ErrorMessage))) .ToList(); } }
  2. Create custom IActionResult.创建自定义 IActionResult。 By default, when display the validation error, it will return BadRequestObjectResult and the HTTP status code is 400. Here we could change the Http Status code.默认显示验证错误时,会返回BadRequestObjectResult,HTTP状态码为400。这里我们可以更改Http状态码。

     public class ValidationFailedResult: ObjectResult { public ValidationFailedResult(ModelStateDictionary modelState): base(new ValidationResultModel(modelState)) { StatusCode = StatusCodes.Status422UnprocessableEntity; //change the http status code to 422. } }
  3. Create Custom Action Filter attribute:创建自定义操作过滤器属性:

     public class ValidateModelAttribute: ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { if (.context.ModelState.IsValid) { context.Result = new ValidationFailedResult(context;ModelState); } } }
  4. Change the default response type to SerializableError in Startup.ConfigureServices:在 Startup.ConfigureServices 中将默认响应类型更改为 SerializableError:

     services.AddControllers().ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var result = new ValidationFailedResult(context.ModelState); // TODO: add `using System.Net.Mime;` to resolve MediaTypeNames result.ContentTypes.Add(MediaTypeNames.Application.Json); result.ContentTypes.Add(MediaTypeNames.Application.Xml); return result; }; });
  5. Add the custom action filter at the action method or controller.在操作方法或 controller 添加自定义操作过滤器。

     [HttpPost] [ValidateModel] public async Task<ActionResult<Student>> PostStudent(Student student) {... }
  6. Create a Student model with custom attribute validation (Min18Years):使用自定义属性验证创建学生 model(Min18Years):

     public class Student { [Key] public int Id { get; set; } [Required(ErrorMessage = "Please enter name")] public string Name { get; set; } [Required(ErrorMessage = "Please choose admission date.")] [Display(Name = "Admission Date")] [DataType(DataType.Date)] public DateTime AdmissionDate { get; set; } [Display(Name = "Date of Birth")] [DataType(DataType.Date)] [Min18Years] public DateTime DateofBirth { get; set; } } public class Min18Years: ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var student = (Student)validationContext.ObjectInstance; if (student.DateofBirth == null) return new ValidationResult("Date of Birth is required."); var age = DateTime.Today.Year - student.DateofBirth.Year; if (age <= 0) { return new ValidationResult("MaxResults should be greater than 0"); } return (age >= 18)? ValidationResult.Success: new ValidationResult("Student should be at least 18 years old."); } }

After running the application, the result like this:运行应用程序后,结果如下:

在此处输入图像描述

Reference:参考:

Handle Validation failure errors in ASP.NET Core web APIs 处理 ASP.NET 核心 web API 中的验证失败错误

Handling validation responses for ASP.NET Core Web API 处理 ASP.NET 核心的验证响应 Web API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 ASP.NET Core 5 Web API 控制器操作的失败模型验证结果包装到另一个类中并将响应返回为 OK - How can I wrap failed model validation result of an ASP.NET Core 5 Web API controller action into another class and return response as OK DTO上的ASP.Net Web API验证属性? - ASP.Net Web API Validation Attributes on DTO? 如何在 Asp Net Core 3.1 Web API 中的派生类型列表上实现数据验证属性 - How do I implement data validation attributes on a list of derived types in Asp Net Core 3.1 Web API ASP.NET Core Web API 验证错误处理 - ASP.NET Core Web API Validation Error Handling ASP.NET Core Web API - Fluent Validation 未按预期工作 - ASP.NET Core Web API - Fluent Validation not working as expected 如何为 ASP.NET Core Web api 添加全局验证? - How can i add a global validation for a ASP.NET Core web api? ASP.NET 内核 Email 使用 API 进行验证 - ASP.NET Core Email Validation with API ASP.NET 核心 Web API - 流利的验证不是针对 Z37A6259CC0C1DAE299A78668 进行验证 - ASP.NET Core Web API - Fluent Validation not validation against null datetime ASP.NET Web API十进制验证 - ASP.NET Web API decimal validation ASP.NET Web API 2控制器中的模型验证并在不同的验证上返回不同的状态代码失败 - Model Validation in ASP.NET Web API 2 Controller and return different Status Codes on different validation fails
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM