Use custom validation responses with fluent validation

前端 未结 4 1160
天命终不由人
天命终不由人 2020-12-29 12:46

Hello I am trying to get custom validation response for my webApi using .NET Core.

Here I want to have response model like

[{
  ErrorCode:
  ErrorFi         


        
4条回答
  •  时光说笑
    2020-12-29 13:09

    As for me, it's better to use the following code in ASP.NET Core project

      services.AddMvc().ConfigureApiBehaviorOptions(options =>
      {
        options.InvalidModelStateResponseFactory = c =>
        {
          var errors = string.Join('\n', c.ModelState.Values.Where(v => v.Errors.Count > 0)
            .SelectMany(v => v.Errors)
            .Select(v => v.ErrorMessage));
    
          return new BadRequestObjectResult(new
          {
            ErrorCode = "Your validation error code",
            Message = errors
          });
        };
      });
    

    Also take into account that instead of anonymous object you can use your concrete type. For example,

         new BadRequestObjectResult(new ValidationErrorViewModel
          {
            ErrorCode = "Your validation error code",
            Message = errors
          });
    

提交回复
热议问题