How to do model validation in every method in ASP.NET Core Web API?

后端 未结 3 1360
孤城傲影
孤城傲影 2021-02-05 13:24

I am getting into ASP.NET Core 2.0 with Web API. One of my first methods are my login:

/// 
/// API endpoint to login a user
/// 
/         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-05 14:16

    How to check the model state?

    Check the controller's ModelState in the action to get the state of the model.

    getting a readable string out of all errors and return a BadRequest with this error?

    Use BadRequest(ModelState) to return HTTP bad request response which will inspect the model state and construct message using errors.

    Completed code

    /// 
    /// API endpoint to login a user
    /// 
    /// The login data
    /// Unauthorizied if the login fails, The jwt token as string if the login succeded
    [AllowAnonymous]
    [Route("login")]
    [HttpPost]
    public IActionResult Login([FromBody]LoginData data) {
        if(ModelState.IsValid) {
            var token = _manager.ValidateCredentialsAndGenerateToken(data);
            if (token == null) {
                return Unauthorized();
            } else {
                return Ok(token);
            }
        }
        return BadRequest(ModelState);
    }
    

    Of course I could write it all myself in a helper method... But I thought about a filter maybe?

    To avoid the repeated ModelState.IsValid code in every action where model validation is required you can create a filter to check the model state and short-circuit the request.

    For example

    public class ValidateModelAttribute : ActionFilterAttribute {
        public override void OnActionExecuting(ActionExecutingContext context) {
            if (!context.ModelState.IsValid) {
                context.Result = new BadRequestObjectResult(context.ModelState);
            }
        }
    }
    

    Can be applied to the action directly

    [ValidateModel] //<-- validation
    [AllowAnonymous]
    [Route("login")]
    [HttpPost]
    public IActionResult Login([FromBody]LoginData data) {
        var token = _manager.ValidateCredentialsAndGenerateToken(data);
        if (token == null) {
            return Unauthorized();
        } else {
            return Ok(token);
        }    
    }
    

    or added globally to be applied to all request where model state should be checked.

    Reference Model validation in ASP.NET Core MVC

提交回复
热议问题