Zapnologica
Zapnologica

Reputation: 22566

How to get a null value if the header doesn't exist

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?

Upvotes: 6

Views: 26763

Answers (7)

anAgent
anAgent

Reputation: 2780

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');
}

Upvotes: 4

Heisenberg
Heisenberg

Reputation: 85

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;

Upvotes: 5

mamashare
mamashare

Reputation: 409

if (Context.Request.Headers.ContainsKey("Token"))
{
      var token = Context.Request.Headers["Token"].Value;         
      return token;
}
else 
      return null;

Upvotes: -1

Jpsy
Jpsy

Reputation: 20892

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;

Upvotes: 3

sujoy ghosh
sujoy ghosh

Reputation: 1

Try using this:

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

Upvotes: 0

Ehsan
Ehsan

Reputation: 32721

you can do this

if (Context.Request.Headers["Token"] != null)
{
      var token = Context.Request.Headers.GetValues("Token");         
      return token;
}
else 
      return null;

Upvotes: 9

landvaarder
landvaarder

Reputation: 7

You could use the Try Catch logic:

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

catch
{
    var token = null;
}

Upvotes: -1

Related Questions