首页 > 解决方案 > 如何验证 asp.net core 3.0 web api 的获取请求中的参数?

问题描述

我想验证 web api 的 get 请求中的参数。如何实现这一点。

代码:

[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());  
}

此处 String id 不得包含任何符号或字母。

标签: c#asp.net-coreasp.net-web-api.net-coreasp.net-core-3.1

解决方案


您可以使用正则表达式验证 id 参数来解决此问题,如果 id 与模式不匹配,您应该返回 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

请让我知道这可不可以帮你。


推荐阅读