Search code examples
c#asp.net.nethttpwebrequest

HTTPWebRequest, How to prevent host/header value from changing case


I am using a HttpWebrequest (.Net 4.0) to talk to my server with this code. My problem is, the client object converts the 'Host' part of the request to lowercase (in my case "TETRA_20") before writing it to wire. Hence my server rejects this HTTP request.

Has someone faced a similar problem and fixed it? Is this an issue with the .Net framework?

HttpWebRequest client = (HttpWebRequest)WebRequest.Create(uri);
WebHeaderCollection myWebHeaderCollection = client.Headers;
client.SendChunked = false;

if (hostAlias != null)
   client.Host = "TETRA_20";
client.UserAgent ="Mozilla/5.0 (Windows NT 5.1; rv:11.0) Gecko/20100101 Firefox/11.0";                
client.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
client.KeepAlive = true;

myWebHeaderCollection.Set("Cache-Control", "max-age=0");
myWebHeaderCollection.Set("Accept-Encoding", "gzip,deflate");
myWebHeaderCollection.Set("Accept-Language", "en-US,en;q=0.5");

WebResponse responseData = client.GetResponse();

Solution

  • Found this through google. RFC2616 (section 3.2.3) states that host header evaluation MUST be case insensitive. So it is a good practice to set the Host header value to lower case before ...

    3.2.3 URI Comparison

    When comparing two URIs to decide if they match or not, a client SHOULD use a case-sensitive octet-by-octet comparison of the entire URIs, with these exceptions:

    • A port that is empty or not given is equivalent to the default port for that URI-reference;
      • Comparisons of host names MUST be case-insensitive;
      • Comparisons of scheme names MUST be case-insensitive;
      • An empty abs_path is equivalent to an abs_path of "/".