将此扩展方法添加到您的代码中:
public static Uri UrlOriginal(this HttpRequestBase request)
{
string hostHeader = request.Headers["host"];
return new Uri(string.Format("{0}://{1}{2}",
request.Url.Scheme,
hostHeader,
request.RawUrl));
}
然后你可以从RequestContext.HttpContext.Request 属性中执行它。
Asp.Net 中存在一个错误(可以避开,见下文),该错误出现在使用端口 80 以外的端口用于本地网站的机器上(如果内部网站通过负载平衡发布,这是一个大问题虚拟 IP 和端口在内部用于发布规则),因此 Asp.Net总是在 AbsoluteUri 属性上添加端口 - 即使原始请求不使用它。
此代码确保在任何负载平衡等发生之前,返回的 url 始终等于浏览器最初请求的 Url(包括端口 - 因为它将包含在主机标头中) .
至少,它在我们的(相当复杂的!)环境中是这样的:)
如果在重写主机标头之间有任何时髦的代理,那么这也不起作用。
2013 年 7 月 30 日更新
正如@KevinJones 在下面的 cmets 中提到的 - 我在下一节中提到的设置已在此处记录:http://msdn.microsoft.com/en-us/library/hh975440.aspx
虽然我不得不说我在尝试时无法让它工作 - 但这可能只是我打错字或什么的。
2012 年 7 月 9 日更新
我不久前遇到了这个问题,并打算更新这个答案,但从未更新过。当有人对此答案投赞成票时,我想我现在应该这样做。
我在 Asp.Net 中提到的“错误”可以通过一个明显未记录的 appSettings 值来控制 - 称为 'aspnet:UseHostHeaderForRequest' - 即:
<appSettings>
<add key="aspnet:UseHostHeaderForRequest" value="true" />
</appSettings>
我在查看 ILSpy 中的 HttpRequest.Url 时遇到了这个问题 - 由该 ILSpy 视图中的以下复制/粘贴左侧的 ---> 指示:
public Uri Url
{
get
{
if (this._url == null && this._wr != null)
{
string text = this.QueryStringText;
if (!string.IsNullOrEmpty(text))
{
text = "?" + HttpEncoder.CollapsePercentUFromStringInternal(text,
this.QueryStringEncoding);
}
---> if (AppSettings.UseHostHeaderForRequestUrl)
{
string knownRequestHeader = this._wr.GetKnownRequestHeader(28);
try
{
if (!string.IsNullOrEmpty(knownRequestHeader))
{
this._url = new Uri(string.Concat(new string[]
{
this._wr.GetProtocol(),
"://",
knownRequestHeader,
this.Path,
text
}));
}
}
catch (UriFormatException)
{ }
}
if (this._url == null) { /* build from server name and port */
...
我个人没有使用过它——它没有记录,因此不能保证会继续存在——但它可能会做我上面提到的同样的事情。为了提高搜索结果的相关性 - 并感谢其他似乎发现了这一点的人 - the 'aspnet:UseHostHeaderForRequest' setting has also been mentioned by Nick Aceves on Twitter