如何验证 asp.net core 3.0 web api 的获取请求中的参数?

How to Validate parameter in asp.net core 3.0 web api's get request?

我想验证网络 api 的获取请求中的参数。如何实现。

代码:

[HttpGet("{id}")]

public async Task<ActionResult<Schedd>> GetSchedd(string id)  
{   
    return Ok(await _context.Schedds.FromSqlRaw<Schedd>("sp_userprofile {0},{1},{2}", id, 7, null).ToListAsync());  
}

此处字符串 id 不能包含任何符号或字母。

您可以通过正则表达式验证 id 参数来解决此问题,如果 id 与模式不匹配,您应该 return 400 http 状态(错误请求):

[HttpGet("{id}")]
public async Task<ActionResult<Schedd>> GetScheddAsync(string id)
{
    // Define the regular expression
    var pattern = "...";
    
    // Validate id parameter with pattern using a regular expression
    var match = Regex.Match(id, pattern);

    if (!match.Success)
    {
        ModelState.AddModelError("Id", "The Id must not contains any symbol or alphabet");

        return BadRequest(ModelState);
    }

    return Ok(await _context.Schedds.FromSqlRaw<Schedd>("sp_userprofile {0},{1},{2}", id, 7, null).ToListAsync());
}

您还需要导入以下命名空间:System.Text.RegularExpressions

如果有帮助,请告诉我。

您可以使用 model validation attribute 来验证参数:

通过继承 System.ComponentModel.DataAnnotations.ValidationAttribute 并覆盖 ValidationResult 以禁止字母或符号(即非数字)字符(您可以遍历每个字符并将其与 0-9 进行比较,但在这里使用正则表达式更简洁):

using System.ComponentModel.DataAnnotations.ValidationAttribute;

public class NumericStringAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (!ValidationRegex.IsMatch(value.ToString()))
        {
            return new ValidationResult("Numeric field must not have a non-numeric character.");
        }

        return ValidationResult.Success;
    }

    // Keep the expression compiled to improve performance.
    private static readonly Regex ValidationRegex = new Regex(@"^[0-9]*$", RegexOptions.Compiled);
}

现在您可以将此属性应用于您的参数:

public async Task<ActionResult<Schedd>> GetSchedd([NumericString] string id)

如果验证失败,这将导致框架将 ModelState.IsValid 设置为 false,您现在可以在函数体内检查,并根据需要 return 错误请求。

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

如果您已将 ApiControllerAttribute 应用到您的控制器,则不需要此部分,因为验证错误会由框架使用 BadRequest 自动处理。