简体   繁体   中英

Return Custom ValidationResult and access it from controller in Asp.Net Core

I'm writing a custom validation attribute for validating the model and I need some additional information other than what ValidationResult offers. I need to return ErrorMessage and ErrorCode and access it in the controller class so that I can send it in the response payload.

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

    protected CustomValidationResult(ValidationResult validationResult) : base(validationResult)
    {
    }
}

public class Mandatory : RequiredAttribute
{
    public int ErrorCode { get; set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        ErrorCode = 10;

        var result = base.IsValid(value, validationContext);

        ErrorCode = 10;

        return new CustomValidationResult(result)
        {
            ErrorCode = ErrorCode
        };
    }
}

I need to get the ErrorCode out in the controller, if ModelState.IsValid fails.

Thanks in advance.

From a controller you can return for eg:- if

if(!ModelState.IsValid)
{
return BadRequest(ModelState)
}

If the Model is decorated with ErrorMessage, for eg:

Class TypeA
{

[Required[ErrorMessage="Should not be null"]]
public string Name;

}

The error message will be returned when the model state is returned as part of the BadRequest.

If you have any custom validation , error can be added to the ModelState as below from the controller API:

for eg:-

if(typeA.Name == "TestName")
{
    ModelState.AddModelError("Name","TestName is not a valid name.");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM