WCF:OperationContext.IncomingMessageProperties.Via返回错误的URI

时间:2011-03-08 18:31:20

标签: c# wcf iis .net-4.0

我在IIS中托管WCF服务。我在IIS中为站点设置了多个主机名绑定。但是,在向任何非默认绑定发出请求时,OperationContext.IncomingMessageProperties.Via属性不会报告正确的URL。报告的URL使用默认绑定的主机名作为基础,具有相同的路径和查询字符串。

例如,假设以下绑定:

http://subfoo.services.myapp.com (first/default entry)
http://subbar.services.myapp.com

http://subbar.services.myapp.com/someservice?id=123

提出请求时

Via属性将请求URI报告为:http://subfoo.services.myapp.com/someservice?id=123

如何获取具有所请求的实际主机名的URL?

1 个答案:

答案 0 :(得分:6)

有可能,只是有点牵扯。您需要获取HTTP主机标头,并替换IncomingMessageProperties.Via Uri的主机段。以下是一些带注释的示例代码:

OperationContext operationContext = OperationContext.Current;
HttpRequestMessageProperty httpRequest = operationContext.IncomingMessageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
if (httpRequest != null)
{
    // Get the OperationContext request Uri:
    Uri viaUri = operationContext.IncomingMessageProperties.Via;
    // Get the HTTP Host Header value:
    string host = httpRequest.Headers[System.Net.HttpRequestHeader.Host];
    // Build a new Uri replacing the host component of the Via Uri:
    var uriBuilder = new UriBuilder(viaUri) { Host = host };

    // This is the Uri which was requested:
    string originalRequestUri = uriBuilder.Uri.AbsoluteUri;
}

HTH:)