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?
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.
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 .
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.
you can do this
if (Context.Request.Headers["Token"] != null)
{
var token = Context.Request.Headers.GetValues("Token");
return token;
}
else
return null;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With