Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read HTTP request headers in a WCF web service?

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 
like image 328
b w Avatar asked Sep 18 '13 16:09

b w


People also ask

How do I read request headers?

Reading Request Headers from Servlets Reading headers is very straightforward; just call the getHeader method of the HttpServletRequest , which returns a String if the header was supplied on this request, null otherwise.

How do I add a custom HTTP header to every WCF call?

You can apply the behavior via an attribute or via configuration using a behavior extension element. Here is a great example of how to add an HTTP user-agent header to all request messages. I am using this in a few of my clients.

How can I see the response header of a website?

View headers with browser development toolsSelect the Network tab. You may need to refresh to view all of the requests made for the page. Select a request to view the corresponding response headers.


2 Answers

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("-------------------------------------------------------"); 
like image 128
sinfere Avatar answered Sep 29 '22 20:09

sinfere


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

IncomingWebRequestContext woc = WebOperationContext.Current.IncomingRequest;  string applicationheader = woc.Headers["HeaderName"]; 
like image 23
Slack Shot Avatar answered Sep 29 '22 19:09

Slack Shot