c# - 无法检查请求中 header 值的空值

标签 c# asp.net-web-api httprequest

我尝试获取如下所示的 header 值 -

IEnumerable<string> headerValues = request.Headers.GetValues("MyCustomerId");
var id = headerValues.FirstOrDefault();

如果 header 值为 null 或不存在,则抛出错误 - InvalidOperationException

GetValues 的 null 检查不提供任何值,因为它永远不会返回 null。如果 header 不存在,您将得到一个 InvalidOperationException

有什么技巧吗?

最佳答案

您可以像这样检查是否为 null:

 if(System.Web.HttpContext.Current.Request.Headers["MyCustomerId"] != null)
   {
      // do something
   }

久经考验

关于c# - 无法检查请求中 header 值的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35452709/

相关文章:

file-upload - 如何创建包含多个 FileHeaders 的 http 请求?

c# - WebApi2 Controller 方法中的条件绑定(bind)

asp.net - 无法使用快速修复导入 namespace (Visual Studio Code)

c# - 当您在 C# 中将枚举转换为 int 时,幕后会发生什么?

c# - 构建名称字段为 A 或 B 的 QueryExpression

java - 使用 gson 将日期从 c# webapi 交换到 java

ios - 在 iOS 中发出 HTTP 请求的正确位置在哪里?

php - 像 requestbin PHP 一样请求捕获

c# - 是否有更短/更简单的 for 循环版本 x 次?

c# - 如何使用 C# Bot Framework 创建图表?