[c#] Getting a Request.Headers value

Very simple I'm sure, but driving me up the wall! There is a component that I use in my web application that identifies itself during a web request by adding the header "XYZComponent=true" - the problem I'm having is, how do you check for this in your view?

The following wont work:

if (Request.Headers["XYZComponent"].Count() > 0)

Nor this:

if (Request.Headers.AllKeys.Where(k => k == "XYZComponent").Count() > 0)

Both throw exceptions if the header variable has not been set. Any help would be most appreciated.

The answer is


Firstly you don't do this in your view. You do it in the controller and return a view model to the view so that the view doesn't need to care about custom HTTP headers but just displaying data on the view model:

public ActionResult Index()
{
    var xyzComponent = Request.Headers["xyzComponent"];
    var model = new MyModel 
    {
        IsCustomHeaderSet = (xyzComponent != null)
    }
    return View(model);
}

The following code should allow you to check for the existance of the header you're after in Request.Headers:

if (Request.Headers.AllKeys.Contains("XYZComponent"))
{
    // Can now check if the value is true:
    var value = Convert.ToBoolean(Request.Headers["XYZComponent"]);
}

string strHeader = Request.Headers["XYZComponent"]
bool bHeader = Boolean.TryParse(strHeader, out bHeader ) && bHeader;

if "true" than true
if "false" or anything else ("fooBar") than false

or

string strHeader = Request.Headers["XYZComponent"]
bool b;
bool? bHeader = Boolean.TryParse(strHeader, out b) ? b : default(bool?);

if "true" than true
if "false" than false
else ("fooBar") than null

if ((Request.Headers["XYZComponent"] ?? "") == "true")
{
    // header is present and set to "true"
}

Header exists:

if (Request.Headers["XYZComponent"] != null)

or even better:

string xyzHeader = Request.Headers["XYZComponent"];
bool isXYZ;

if (bool.TryParse(xyzHeader, out isXYZ) && isXYZ)

which will check whether it is set to true. This should be fool-proof because it does not care on leading/trailing whitespace and is case-insensitive (bool.TryParse does work on null)

Addon: You could make this more simple with this extension method which returns a nullable boolean. It should work on both invalid input and null.

public static bool? ToBoolean(this string s)
{
    bool result;

    if (bool.TryParse(s, out result))
        return result;
    else
        return null;
}

Usage (because this is an extension method and not instance method this will not throw an exception on null - it may be confusing, though):

if (Request.Headers["XYZComponent"].ToBoolean() == true)

In dotnet core, Request.Headers["X-MyCustomHeader"] returns StringValues which will not be null. You can check the count though to make sure it found your header as follows:

var myHeaderValue = Request.Headers["X-MyCustomHeader"];
if(myHeaderValue.Count == 0) return Unauthorized();
string myHeader = myHeaderValue.ToString(); //For illustration purposes.

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to httpwebrequest

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send How to properly make a http web GET request Send JSON via POST in C# and Receive the JSON returned? How to create JSON post to api using C# Use C# HttpWebRequest to send json to web service Post form data using HttpWebRequest HttpWebRequest-The remote server returned an error: (400) Bad Request Get host domain from URL? How to ignore the certificate check when ssl Receiving JSON data back from HTTP request

Examples related to http-headers

Set cookies for cross origin requests Adding a HTTP header to the Angular HttpClient doesn't send the header, why? Passing headers with axios POST request What is HTTP "Host" header? CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response Using Axios GET with Authorization Header in React-Native App Axios get access to response header fields Custom header to HttpClient request Send multipart/form-data files with angular using $http Best HTTP Authorization header type for JWT

Examples related to namevaluecollection

Parse a URI String into Name-Value Collection Check if Key Exists in NameValueCollection Getting a Request.Headers value