Click here to Skip to main content
15,892,927 members
Articles / Web Development / ASP.NET

A fast way to get a specific header value

Rate me:
Please Sign up or sign in to vote.
3.00/5 (1 vote)
19 Mar 2009MIT 26.9K   6   16
A fast way to get a specific header value.

Introduction

This article explains a fast way to get a specific header value. This is just a more generic version of http://dotnetperls.com/Content/GZIP-Request.aspx.

Although my method is slightly slower (performance difference is almost unnoticeable), this way, you don't need to hard-code for all possible headers. I also tried comparing a char using a loop but it's slower.

Using the code

C#
public static string GetHeaderValue(NameValueCollection headers, string key)
{
    for (int i = 0; i < headers.Count; i++)
    {
        if (string.Equals(headers.GetKey(i), key, 
            System.StringComparison.OrdinalIgnoreCase))
        {
            return headers.Get(i);
        }
    }

    return string.Empty;
}

For example, if you want to find "Accept-Encoding", just call GetHeaderValue(request.Headers, "Accept-Encoding"), assuming you have an instance of an HttpRequest called request.

Performance test:

Just put the following code into a console program:

C#
private static NameValueCollection headers = new NameValueCollection();
        
static void Main(string[] args)
{            
    Console.ReadLine();
    GetHeaderValuePerformanceTest();
    Console.ReadLine();
}

static void GetHeaderValuePerformanceTest()
{
    
    headers.Add("Content-Type", "application/json");
    headers.Add("Accept", "text/html,application/xhtml+xml," + 
                "application/xml;q=0.9,*/*;q=0.8");
    headers.Add("Accept-Language", "en-us,en;q=0.5");
    headers.Add("Accept-Encoding", "gzip");
    headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    headers.Add("Connection", "keep-alive");

    int iterations = 1000000;
    Stopwatch watch;

    // GetHeaderValue
    watch = Stopwatch.StartNew();
    for (int i = 0; i < iterations; i++)
    {
        var result = GetHeaderValue(headers, "Accept-Encoding");
    }
    watch.Stop();
    Console.Write("GetHeaderValue: " + watch.ElapsedMilliseconds.ToString());
    Console.WriteLine();

    // Indexer
    watch = Stopwatch.StartNew();
    for (int i = 0; i < iterations; i++)
    {
        var result = headers["Accept-Encoding"];
    }

    watch.Stop();
    Console.Write("Indexer: " + watch.ElapsedMilliseconds.ToString());
    Console.WriteLine();
}

static string GetHeaderValue(NameValueCollection headers, string key)
{
    for (int i = 0; i < headers.Count; i++)
    {
        if (string.Equals(headers.GetKey(i), key, 
            System.StringComparison.OrdinalIgnoreCase))
        {
            return headers.Get(i);
        }
    }

    return string.Empty;
}

Results of 1000000 loops:

GetHeaderValue:344ms
Indexer:1350ms

Points of interest

This method will be soon added to my project Apprender.Common 2.6 hosted at http://apprender.codeplex.com/.

History

  • March 17, 2009: Posted.
  • March 18, 2009: Added Performance Test, updated code.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Canada Canada
My Projects:
- Apprender.Common http://apprender.codeplex.com/

Education History:
- Junior High: YUSS
- Senior High: Harry Ainlay
- University: undecided

Comments and Discussions

 
Generalok article Pin
Donsw10-Apr-09 7:41
Donsw10-Apr-09 7:41 
GeneralThink a bit Pin
scalp20-Mar-09 2:22
scalp20-Mar-09 2:22 
QuestionWhy? Pin
ZakPatat18-Mar-09 18:56
ZakPatat18-Mar-09 18:56 
AnswerRe: Why? Pin
Scoby918-Mar-09 19:54
Scoby918-Mar-09 19:54 
you're absolutely right. you can use Request.Headers property if you're working on a code-behind page, however, since i'm building a class library, i cannot get access to such property(although technically you could get headers through HttpContext.Current.Request.Headers, it adds a little more overhead of retrieving HttpContext and HttpRequest).
And another thing is it's not just 25 or 50ms faster, it's way faster than directly retrieving header using indexer(HttpRequest.Headers["Accept-Encoding"]). although performance gain may seem unnoticeable at the beginning, but what about a site that has more than 100 or even just 10 requests per second, it can actually save whole lot of time.
since this method is relatively easy, i guess you could just type it up Poke tongue | ;-P (kinda tedious) every time you need it.
anyways, thanks for your reply. this is my first article here, and you're the first person to reply. in the future i'll probably publish tutorials on how to build more advanced components like the one i built(source codes are available at http://apprender.codeplex.com/)
GeneralRe: Why? Pin
jgauffin18-Mar-09 21:12
jgauffin18-Mar-09 21:12 
AnswerRe: Why? Pin
Scoby919-Mar-09 8:16
Scoby919-Mar-09 8:16 
GeneralRe: Why? Pin
jgauffin19-Mar-09 8:40
jgauffin19-Mar-09 8:40 
AnswerRe: Why? Pin
Scoby919-Mar-09 8:48
Scoby919-Mar-09 8:48 
GeneralRe: Why? [modified] Pin
ZakPatat19-Mar-09 9:00
ZakPatat19-Mar-09 9:00 
GeneralRe: Why? Pin
ADLER119-Mar-09 10:37
ADLER119-Mar-09 10:37 
GeneralRe: Why? Pin
ZakPatat19-Mar-09 11:18
ZakPatat19-Mar-09 11:18 
GeneralRe: Why? Pin
ADLER119-Mar-09 12:12
ADLER119-Mar-09 12:12 
GeneralRe: Why? Pin
ZakPatat20-Mar-09 5:47
ZakPatat20-Mar-09 5:47 
GeneralRe: Why? Pin
Scoby920-Mar-09 8:24
Scoby920-Mar-09 8:24 
GeneralRe: Why? Pin
TimMerksem24-Mar-09 6:14
TimMerksem24-Mar-09 6:14 
AnswerRe: Why? [modified] Pin
Scoby924-Mar-09 12:07
Scoby924-Mar-09 12:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.