如何读取 WCF Web 服务中的 HTTP 请求标头? [英] How to read HTTP request headers in a WCF web service?
问题描述
在 WCF Web 服务中,如何读取 HTTP/HTTPS 请求标头?在这种情况下,我试图确定客户端使用的原始 URL 主机.这可能在来自负载均衡器的 X-Forwarded-Host 标头中,或者在主机标头中(如果它是直接框).
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.
我已经尝试过 OperationContext.Current.IncomingMessageHeaders.FindHeader
但我认为这是在查看 SOAP 标头而不是 HTTP 标头.
I've tried OperationContext.Current.IncomingMessageHeaders.FindHeader
but i think this is looking at SOAP headers rather than HTTP headers.
那么,如何读取 HTTP 标头?当然,这是一个简单的问题,我遗漏了一些明显的东西.
So, how to read HTTP headers? Surely this is a simple question and i'm missing something obvious.
编辑 - @sinfere 的回答几乎正是我所需要的.为了完整起见,这是我最终得到的:
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("-------------------------------------------------------");
这篇关于如何读取 WCF Web 服务中的 HTTP 请求标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!