[英]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:
检查以下示例代码:
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(); } }
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. } }
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); } } }
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; }; });
Add the custom action filter at the action method or controller.在操作方法或 controller 添加自定义操作过滤器。
[HttpPost] [ValidateModel] public async Task<ActionResult<Student>> PostStudent(Student student) {... }
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.