2

i need to create a Create Custom Return Validate in Asp Core 2.2 in WebApi .

First Step :

I Create a on OnResultExecuting :

public override void OnResultExecuting(ResultExecutingContext context)
{
 if (context.Result is BadRequestObjectResult badRequestObjectResult)
        {
            var message = badRequestObjectResult.Value.ToString();
            if (badRequestObjectResult.Value is SerializableError errors)
            {
                var errorMessages = errors.SelectMany(p => (string[])p.Value).Distinct();
                message = string.Join(" | ", errorMessages);
            }
            context.Result = new JsonResult(new ReturnResult(false, ResultStatus.BadRequest, message))
            { StatusCode = badRequestObjectResult.StatusCode };
        }
}

Second Step :

i Create a IValidatableObject in UserDto :

 public class UserDto : IValidatableObject
{
    [Required]
    public string Name { get; set; }
    [Required]
    public string Family { get; set; }
    [Required]
    public string Password { get; set; }
    [Required]
    public string Username { get; set; }
    [Required]
    public string Email { get; set; }
    [Required]
    public string Phone { get; set; }
    [Required]
    public GenderType Gender { get; set; }


    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        foreach (var item in ValidateList.UsernameBanList)
            if (Username.Equals(item, StringComparison.OrdinalIgnoreCase))
                yield return new ValidationResult("Username Invalid", new[] { nameof(Username) });
        foreach (var item in ValidateList.PasswordBanList)
            if (Password.Equals(item, StringComparison.OrdinalIgnoreCase))
                yield return new ValidationResult("Password Invalid, new[] { nameof(Password) });
        foreach (var item in ValidateList.EmailBanList)
            if (Email.Equals(item, StringComparison.OrdinalIgnoreCase))
                yield return new ValidationResult("Email Invalid", new[] { nameof(Email) });
    }
}

Third Step :

I Create a ReturnResult Class :

public class ReturnResult
{
    public bool Success { get; }
    public ResultStatus Status { get; }
    public string Message { get; }

    public ReturnResult(bool Success, ResultStatus Status, string Message = null)
    {
        this.Success = Success;
        this.Status = Status;
        this.Message = Message ?? Status.ToDisplay();
    }

    #region implicit operator
    public static implicit operator ReturnResult(OkResult result)
    {
        return new ReturnResult(true, ResultStatus.Success);
    }

    public static implicit operator ReturnResult(BadRequestResult result)
    {
        return new ReturnResult(false, ResultStatus.BadRequest);
    }

    public static implicit operator ReturnResult(BadRequestObjectResult result)
    {
        var message = result.ToString();
        if (result.Value is SerializableError error)
        {
            var errorMessage = error.SelectMany(p => (string[])p.Value).Distinct();
            message = string.Join(" | ", errorMessage);
        }
        return new ReturnResult(false, ResultStatus.BadRequest, message);
    }

    public static implicit operator ReturnResult(ContentResult result)
    {
        return new ReturnResult(true, ResultStatus.Success, result.Content);
    }

    public static implicit operator ReturnResult(NotFoundResult result)
    {
        return new ReturnResult(false, ResultStatus.NotFound);
    }
    #endregion
}

Now All Return in Api by this Format :

{
"success": true,
"status": 0,
"message": "success process"
 }

in UserDto i Create a Validate in for Username and Password and Email then i need to return all error of them return by this format :

{
"success": true,
"status": 0,
"message": "Email Invalid | Password Invalid | Username Invalid"
 }

but it not show me by this format , it show me this format :

{
"success": false,
"status": 2,
"message": "Microsoft.AspNetCore.Mvc.ValidationProblemDetails"
 }

how can i solve this problem ????

3
  • Is there any demo to reproduce your issue? I made a test with your code, and it works correctly, check result. Try to debug your code line by line to see where it return Microsoft.AspNetCore.Mvc.ValidationProblemDetails. Commented Mar 25, 2019 at 3:02
  • Probably badRequestObjectResult.Value.ToString() returns the "Microsoft.AspNetCore.Mvc.ValidationProblemDetails", and the next if condition is not executed. It's better to say what you wrote in the controller Commented Mar 31, 2019 at 9:19
  • I have the same code and the same result. What really caused the error? Commented Jan 31, 2023 at 16:16

1 Answer 1

2

try it:

public static implicit operator ReturnResult(BadRequestObjectResult result)
        {
            System.Reflection.PropertyInfo pi = result.Value.GetType().GetProperty("Errors");
            Dictionary<string, string[]> errors = (Dictionary<string, string[]>)(pi.GetValue(result.Value, null));

            var message = result.ToString();
            var errorMessage = error.SelectMany(p => p.Value).Distinct();
            message = string.Join(" | ", errorMessage);
            return new ReturnResult(false, ResultStatus.BadRequest, message);
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Can you say why "result.Value is SerializableError error" doesn't recognize the result.Value as SerializableError?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.