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
4

2 回答 2

50

尝试WebOperationContext.Current.IncomingRequest.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("-------------------------------------------------------");
于 2013-09-18T16:45:27.337 回答
24

这就是我在我的 Azure WCF Web 服务之一中阅读它们的方式。

IncomingWebRequestContext woc = WebOperationContext.Current.IncomingRequest;

string applicationheader = woc.Headers["HeaderName"];
于 2013-09-18T16:43:28.973 回答