43

In a WCF web service, how does one read an HTTP/HTTPS request header? In this case, i'm trying to determine the original URL host the client used. This might be in the X-Forwarded-Host header from a load balancer, or in the Host header if it's direct-box.

I've tried OperationContext.Current.IncomingMessageHeaders.FindHeader but i think this is looking at SOAP headers rather than HTTP headers.

So, how to read HTTP headers? Surely this is a simple question and i'm missing something obvious.

EDIT - @sinfere's answer was almost exactly what i needed. For completeness, here's what i ended up with:

IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
WebHeaderCollection headers = request.Headers;
string host = null;

if (headers["X-Forwarded-Host"] != null)
    host = headers["X-Forwarded-Host"];
else if (headers["Host"] != null)
    host = headers["Host"];
else 
    host = defaulthost; // set from a config value
b w
  • 4,553
  • 4
  • 31
  • 36
  • use ... WebOperationContext.Current.IncomingRequest.Headers – Seymour Sep 18 '13 at 16:51
  • 1
    While technically not a header, WCF disposes the content from the original HTTP Request so you will not be able to access the content of a Request inside your service. You can however, grab this before a service method is invoked inside a OperationsHandler – Itanex Sep 18 '13 at 16:53

2 Answers2

51

Try WebOperationContext.Current.IncomingRequest.Headers

I use following codes to see all headers :

IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
WebHeaderCollection headers = request.Headers;

Console.WriteLine("-------------------------------------------------------");
Console.WriteLine(request.Method + " " + request.UriTemplateMatch.RequestUri.AbsolutePath);
foreach (string headerName in headers.AllKeys)
{
  Console.WriteLine(headerName + ": " + headers[headerName]);
}
Console.WriteLine("-------------------------------------------------------");
GGO
  • 2,678
  • 4
  • 20
  • 42
sinfere
  • 927
  • 8
  • 9
  • Not all of this worked (the second `Consol.WriteLine` line) but the rest got me there. Thanks. +1 – b w Sep 19 '13 at 15:08
24

This is how I read them in one of my Azure WCF web services.

IncomingWebRequestContext woc = WebOperationContext.Current.IncomingRequest;

string applicationheader = woc.Headers["HeaderName"];
Slack Shot
  • 1,090
  • 6
  • 10