6

I am using the request context to get the value of the header called "token".

 var token = context.request.Headers.GetValues("Token")

Now If the header exists. This all works hundreds, But now if the header doesn't exist, I want it to return null. But instead it throws an exception System.InvalidOperationExecption

Is my only option to throw a try catch around it?

Zapnologica
  • 22,170
  • 44
  • 158
  • 253

7 Answers7

9

you can do this

if (Context.Request.Headers["Token"] != null)
{
      var token = Context.Request.Headers.GetValues("Token");         
      return token;
}
else 
      return null;
Ehsan
  • 31,833
  • 6
  • 56
  • 65
  • If `Context.Request.Headers["Token"]` is null and I used `@token` in my view, would that not throw an undefined error? Should your `else` not set `token = null`? – wf4 Mar 11 '14 at 09:17
  • 2
    why set token to null when you can just return it as it is? – Ehsan Mar 11 '14 at 09:17
  • I'm just asking. In the question it was said `"But now if the header doesn't exist, I want it to return null. But instead it throws an exception System.InvalidOperationExecption"`... is that still going to happen? – wf4 Mar 11 '14 at 09:18
  • use it like i have mentioned. – Ehsan Mar 11 '14 at 09:19
4

Below are examples of how to check if the header exists and then if the value is null.

These examples are using DotNet Core 3.1

Checking if it exists - not caring about the value:


if (context.HttpContext.Request.Headers.Any(h => h.Key.Equals("X-SOME-HEADER", StringComparison.InvariantCultureIgnoreCase))) {
    // Success
    _logger.LogInformation('Header found');
} else {
    // Failure
    _logger.LogWarning('Header not found');
}

Checking if it exists and output the value:

if (context.HttpContext.Request.Headers.TryGetValue("X-SOME-HEADER", out var token)) {
    // Found header
    _logger.LogInformation($"Header found. Null:[{!token.Any()}]")
} else {
    // Failure
    _logger.LogWarning('Header not found');
}

TotPeRo
  • 6,561
  • 4
  • 47
  • 60
anAgent
  • 2,550
  • 24
  • 34
4

I've ran into the same issue, when the headers doesn't exists, it would throw an error at me. I've however managed to find an easy way using .NET Core 3.1 and can be done in 1 line and will avoid you getting any of these errors.

But in a nutshell it checks if the headers contains the key "Token", if yes then returns the value else returns null.

string token = HttpContext.Request.Headers.ContainsKey("Token") ? HttpContext.Request.Headers["Token"][0] : null;
Heisenberg
  • 75
  • 1
  • 10
3

The Headers class provides a Contains() method.

Example 1:

if (!request.Headers.Contains("Token"))
    {
        return null;
    }

Example 2:

string token = request.Headers.Contains("Token") ? request.Headers.GetValues("Token").First() : null;
Jpsy
  • 20,077
  • 7
  • 118
  • 115
0

Try using this:

 var token = string.IsNullOrEmpty(context.request.Headers.GetValues("Token")) ? null :
                               context.request.Headers.GetValues("Token");
-1

You could use the Try Catch logic:

try
{
    var token = context.request.Headers.GetValues("Token");
}

catch
{
    var token = null;
}
  • 5
    throwing an exception is a costly operation. Exception should be caught only in exceptional scenarios. Not in your regular code. You should avoid it as much as possible. Not a good solution. – Ehsan Mar 11 '14 at 09:14
-1
if (Context.Request.Headers.ContainsKey("Token"))
{
      var token = Context.Request.Headers["Token"].Value;         
      return token;
}
else 
      return null;
mamashare
  • 399
  • 4
  • 10