C# 如何读取 WCF Web 服务中的 HTTP 请求标头?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18877591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:29:52  来源:igfitidea点击:

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

c#wcfweb-services

提问by b w

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.

在 WCF Web 服务中,如何读取 HTTP/HTTPS 请求标头?在这种情况下,我试图确定客户端使用的原始 URL 主机。这可能在来自负载均衡器的 X-Forwarded-Host 标头中,或者在 Host 标头中(如果它是直接框)。

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

我试过了,OperationContext.Current.IncomingMessageHeaders.FindHeader但我认为这是在查看 SOAP 标头而不是 HTTP 标头。

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

那么,如何读取 HTTP 标头呢?当然,这是一个简单的问题,我遗漏了一些明显的东西。

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

编辑 - @sinfere 的回答几乎正是我所需要的。为了完整起见,这是我最终得到的:

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

采纳答案by sinfere

Try WebOperationContext.Current.IncomingRequest.Headers

尝试 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("-------------------------------------------------------");

回答by Slack Shot

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

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

IncomingWebRequestContext woc = WebOperationContext.Current.IncomingRequest;

string applicationheader = woc.Headers["HeaderName"];