在Web API.Core中,如何在每种方法中进行模型验证? [英] In Web API.Core, how to do Model Validation in every method?

查看:139
本文介绍了在Web API.Core中,如何在每种方法中进行模型验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有Web API的ASP.Net Core 2.0。

I am getting into ASP.Net Core 2.0 with Web API.

我的第一个方法是登录:

One of my first methods are my login:

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

我的 LoginData 使用DataAnnotations:

My LoginData using DataAnnotations:

public class LoginData
{
    [Required]
    [MaxLength(50)]
    public string Username { get; set; }

    [Required]
    public string Password { get; set; }

    [Required]
    [MaxLength(16)]
    public string IpAddress { get; set; }
}

所以我的 ModelState 会在登录时自动填充,例如密码为空(当然,在客户端,以后也应该进行验证)。

So my ModelState is well filled automatically when the login happens and e.g. the password is empty (of course on client side there should be a validation too for it later).

我的问题是:

最好的方法:a)检查模型状态,b)从所有错误中获取可读的字符串,以及C)返回具有此错误的BadRequest?

My question is:
What is the best way to a) check the model state, b) getting a readable string out of all errors and C) return a BadRequest with this error?

当然我可以写

推荐答案


如何检查模型状态?

How to check the model state?

在操作中检查控制器的 ModelState

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


从所有错误中获取可读的字符串并返回具有此错误的BadRequest吗?

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

使用 BadRequest(ModelState)返回HTTP错误请求响应,该响应将检查模型状态并

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

已完成的代码

/// <summary>
/// API endpoint to login a user
/// </summary>
/// <param name="data">The login data</param>
/// <returns>Unauthorizied if the login fails, The jwt token as string if the login succeded</returns>
[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?

为避免重复 ModelState.IsValid 在需要模型验证的每个操作中的代码,您都可以创建一个过滤器来检查模型状态并缩短请求。

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.

例如

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

可以应用于该操作直接

[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.

参考在ASP.NET Core MVC中进行模型验证

这篇关于在Web API.Core中,如何在每种方法中进行模型验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆