如何读取HTTP请求头中的一个WCF Web服务? [英] How to read HTTP request headers in a WCF web service?
问题描述
在一个WCF Web服务,一个人如何读取HTTP / HTTPS请求头?在这种情况下,我试图确定原始URL主机所使用的客户端。这可能是在X - 转发,主机头从负载均衡器,或者在主机头,如果是直接框。
我试过 OperationContext.Current.IncomingMessageHeaders.FindHeader
,但我认为这是在看SOAP头,而不是HTTP标头。
那么,如何读取HTTP头?当然,这是一个简单的问题,我缺少明显的东西。
编辑 - @ sinfere的回答几乎正是我需要的。为了完整起见,这里是我结束了:
IncomingWebRequestContext请求= WebOperationContext.Current.IncomingRequest;
WebHeaderCollection头= request.Headers;
字符串主机= NULL;如果(标题[X - 转发,主机]!= NULL)
主机=标题[X - 转发,主机];
否则,如果(标题[HOST]!= NULL)
主机=标题[主机];
其他
主机= defaulthost; //从配置值设置
尝试WebOperationContext.Current.IncomingRequest.Headers
我用下面的codeS看到所有的标题
IncomingWebRequestContext请求= WebOperationContext.Current.IncomingRequest;
WebHeaderCollection头= request.Headers;Console.WriteLine(--------------------------------------------- ----------);
Console.WriteLine(request.Method ++ request.UriTemplateMatch.RequestUri.AbsolutePath);
的foreach(在headers.AllKeys串headerName)
{
Console.WriteLine(headerName +:+报头[headerName]);
}
Console.WriteLine(--------------------------------------------- ----------);
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
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("-------------------------------------------------------");
这篇关于如何读取HTTP请求头中的一个WCF Web服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!