c# - 如何验证 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 不得包含任何符号或字母。
解决方案
您可以使用正则表达式验证 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
请让我知道这可不可以帮你。
推荐阅读
- css - 在 MS powerapps 控件中使用 react-bootstrap-typeahead 时,下拉列表隐藏在其他输入字段下
- hyperledger-fabric - 中间 CA 不创建 tls-cert.pem
- python - 在同一个类中使用另一个函数的输出
- node.js - 更新矩阵中的元素,该矩阵是嵌套在另一个文档中的文档的字段
- postgresql - Postgres 中的共享扫描
- reactjs - 更改文本输入中的字体大小根据屏幕大小做出本机反应
- javascript - Webpack 外部反应导致 React Hooks 错误
- javascript - 函数中的最小值 40 和最大值 60。我该如何解决?
- python - 访问 WebElement 对象内容的方法有哪些?
- node.js - dpkg 被中断,您必须手动运行 'sudo dpkg --configure -a' 来纠正问题