如何在ASP.NET Core Web API中的每种方法中进行模型验证? [英] How to do model validation in every method in ASP.NET Core Web API?

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

问题描述

我正在使用带有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).

什么是最好的方法

  • 检查模型状态,
  • 从所有错误中获取可读的字符串,并且
  • 返回此错误的 BadRequest 吗?

当然,我可以自己使用辅助方法编写所有内容.但是我可能会考虑使用过滤器?

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

推荐答案

如何检查模型状态?

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

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

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