Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill a dictionary with all request headers

Im able to get request headers one by one when I have the header key name with this method

private string GetHeader(string Name)
{
    IEnumerable<string> headerValues;
    if (Request.Headers.TryGetValues(Name, out headerValues))
    {
        return headerValues.FirstOrDefault();
    }
    else { return ""; }
}

But what I really would like is to get all request headers and store them in a dictionary, something like this

Dictionary<string, string> ss = Request.Headers.ToDictionary(a => a.Key, a => a.Value); 
//this doesn't work

Does anyone know how to do this?

like image 567
Marcus Höglund Avatar asked Sep 16 '16 07:09

Marcus Höglund


1 Answers

You can already enumerate all header values, because Request.Headers being of type HttpRequestHeaders is a IEnumerable<KeyValuePair<string, IEnumerable<string>>>.

So the Value is a IEnumerable<string> and your Dictionary has to change to

Dictionary<string, IEnumerable<string>> ss 
       = Request.Headers.ToDictionary(a => a.Key, a => a.Value);

or if you want to stick to the string value you can join the string enumeration.

Dictionary<string, string> ss 
       = Request.Headers.ToDictionary(a => a.Key, a => string.Join(";", a.Value));
like image 190
Ralf Bönning Avatar answered Sep 28 '22 02:09

Ralf Bönning