Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 796
Zapnologica Avatar asked Mar 11 '14 09:03

Zapnologica


People also ask

Can header values null?

The use of a NULL (0 valued) character within the name or value of an HTTP request Header field is banned by the standard. An attacker embeds NULL characters within the Header field in order to evade detection mechanisms.

How do I find a header value?

get() The get() method of the Headers interface returns a byte string of all the values of a header within a Headers object with a given name. If the requested header doesn't exist in the Headers object, it returns null .

What is a request header?

A request header is an HTTP header that can be used in an HTTP request to provide information about the request context, so that the server can tailor the response. For example, the Accept-* headers indicate the allowed and preferred formats of the response.


2 Answers

you can do this

if (Context.Request.Headers["Token"] != null)
{
      var token = Context.Request.Headers.GetValues("Token");         
      return token;
}
else 
      return null;
like image 162
Ehsan Avatar answered Oct 10 '22 20:10

Ehsan


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;
like image 27
Heisenberg Avatar answered Oct 10 '22 18:10

Heisenberg