webressurs
asked on
Get multiple http header values (Request.Headers.TryGetValues)
In my ASP.NET Web API I need to get up to 10 different http header values. I found this example that shows how to get one single http header value:
If I also need to get header values "Test2", "Test3", "Test4", "Test5" and so on, how can this be done? I guess there is a bad solution to repeat the code above 10 times...
IEnumerable<string> values = new List<string>();
Request.Headers.TryGetValues("Test1", out values);
var test1 = values.First();
If I also need to get header values "Test2", "Test3", "Test4", "Test5" and so on, how can this be done? I guess there is a bad solution to repeat the code above 10 times...
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
This line:
WebHeaderCollection header = request.Headers;
Gives this error:
Cannot implicitly convert type 'System.Net.Http.Headers.H ttpRequest Headers' to 'System.Net.WebHeaderColle ction'
I got a solution that works fine, here is the code:
private string GetHeader(string key)
{
var header = "";
if (Request.Headers.Contains( key))
{
IEnumerable<string> values = new List<string>();
Request.Headers.TryGetValu es(key, out values);
if (!string.IsNullOrEmpty(val ues.First( ))) header = values.First();
}
return header;
}
public IEnumerable<API.Models.Use rCard> GetUsers()
{
var headerTest1 = GetHeader("Test1");
var headerTest2 = GetHeader("Test2");
var headerTest3 = GetHeader("Test3");
var Test1 = headerTest1 != "" ? int.Parse(headerTest1) : 0;
var Test2 = headerTest1 != "" ? int.Parse(headerTest2) : 0;
var Test3 = headerTest1 != "" ? int.Parse(headerTest3) : 0;
.
.
.
}
My code is almost identical to kaufmed example above, hope this is a good solution :)
WebHeaderCollection header = request.Headers;
Gives this error:
Cannot implicitly convert type 'System.Net.Http.Headers.H
I got a solution that works fine, here is the code:
private string GetHeader(string key)
{
var header = "";
if (Request.Headers.Contains(
{
IEnumerable<string> values = new List<string>();
Request.Headers.TryGetValu
if (!string.IsNullOrEmpty(val
}
return header;
}
public IEnumerable<API.Models.Use
{
var headerTest1 = GetHeader("Test1");
var headerTest2 = GetHeader("Test2");
var headerTest3 = GetHeader("Test3");
var Test1 = headerTest1 != "" ? int.Parse(headerTest1) : 0;
var Test2 = headerTest1 != "" ? int.Parse(headerTest2) : 0;
var Test3 = headerTest1 != "" ? int.Parse(headerTest3) : 0;
.
.
.
}
My code is almost identical to kaufmed example above, hope this is a good solution :)
Open in new window