简体   繁体   中英

Model state returns right away .Net Core 5

I have a custom validation attribute

public class IsUsernameAcceptableAttr:ValidationAttribute
{
    
    protected override ValidationResult IsValid(object username, ValidationContext validationContext)
    {
        var _username = username.ToString();
        if (_username.Length<4)
            return new ValidationResult("Username must be at least 4 characters.");
       
        return ValidationResult.Success;

    }
}

in my DTO class I have

 public class UserAccountInformationDTO
    {
        [IsUsernameAcceptableAttr]
        public string Username { get; set; }


    }

In action method I got

public IActionResult UpdateAccountInformationstring(UserAccountInformationDTO accountInfo)
    {
        var ms = ModelState.IsValid;
        return Ok();
        
    }

The issue is when model state hits an error it send a response back in errors as JSON response. I never get to do anything in the controller or alter the response to a format that i want. What else can i do?

You need to specify the source of the parameters

https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-5.0#binding-source-parameter-inference

Update:

Add the following codes to your startup ConfigureServices:

services.Configure<ApiBehaviorOptions>(apiBehaviorOptions => {
    apiBehaviorOptions.SuppressModelStateInvalidFilter = true;
});

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