c# - Web API .net core 2 request 检查请求头不为空
问题描述
如何验证请求的标头 some-header 是否与书的 bookId 匹配?
public IActionResult GetBooks()
{
// if 'some-header' value is empty, null , whitespace or request contains multiple ' some-header' headers then it should return UnauthorizedResult();
// if 'some-header' is not above then it needs to be read from repository
}
public class Book
{
public string bookId {get; set;}
}
解决方案
Request.Headers.GetValues()
will return an IEnumerable<string>
that correspond the headers from the HTTP request , then you can validate wether this contains multiple values or if its only one check if is null or white space ( which includes empty )
Request.Headers.TryGetValue("some-header", out var headers);
if(headers.Count > 1 || string.IsNullOrWhiteSpace(headers.FirstOrDefault())){
return new UnauthorizedResult();
}
推荐阅读
- windows - 是命令提示符和 PowerShell 终端仿真器吗?
- c++ - 如何使用 cpp 中的 windows 库在程序中获取像素的颜色?
- pandas - 通过组合列值在 Altair 中绘制网格堆积条形图
- python - 在 pcolormesh 上覆盖轮廓颜色条
- python - 从另一个python文件调用函数后画布不显示图像
- sql - 为什么这个 sql 片段总是返回 8 或 1?
- python - Python:将一列列表插入Mysql
- python - 在 Python 中使用这个二维数组的更好方法
- python - 有效地将 pandas 数据帧转换为 scipy 稀疏矩阵
- javascript - 如何实现允许用户从前端在图像上绘制点的功能?