我知道这个答案是晚了大约2年半,但我找不到在UrlReferrer
属性彻底写出来,所以我想我会在这里添加此信息。 @ MarcGravell的答案大部分都是正确的,但它错过了另外一种可能性。 HTTP标头中指定的引荐来源的值也可能是无效的URI。
因此,在HttpRequest
上使用UrlReferrer
属性时应该小心。如果您查看UrlReferrer
使用类似ILSpy的方式调用时执行的代码,您会看到它试图解析请求头中的值。如果该标题中的值不是有效的URI,则会得到System.UriFormatException
。
这意味着如果在尝试访问AbsoluteUri
之前简单检查UrlReferrer
,如果引用链接不是有效的URI,可能会导致未处理的异常。如果您需要有效的Uri
或null
,则必须先使用Request.ServerVariables["HTTP_REFERER"]
,然后使用Uri.TryParse
,否则您必须将Request.UriReferrer == null
支票换成try-catch
。
我整理了一个快速演示,以显示UrlReferrer
属性的行为。看看下面的页面为例:
<%@ Page Language="C#" AutoEventWireup="true" %>
<html><body>
<table border="1">
<tr><td>Referrer</td><td><%= GetUrlReferrer() %></td></tr>
</table>
</body></html>
<script runat="server">
public string GetUrlReferrer()
{
try
{
return Request.UrlReferrer == null ? "(None)" : Request.UrlReferrer.ToString();
}
catch (Exception ex)
{
return Request.ServerVariables["HTTP_REFERER"] + " (from Server Variable)";
}
}
</script>
设置此页http://localhost/urlreferrertest.aspx
下运行,然后再尝试使用PowerShell和无效的Uri称其为引用:
> $client = new-object System.Net.WebClient
> $client.Headers.Add("Referer", "http://www%2etest%2e.com/test.html")
> $client.DownloadString("http://localhost/urlreferrertest.aspx")
如果通过步骤您将看到代码Request.UrlReferrer
引发异常,并且http://www%2etest%2e.com/test.html
通过访问ServerVariable
返回。
我想你可以使用'Request.UrlReferrer'。 – yogi 2012-08-09 07:18:37
没有理由对一个合法的问题进行倒票。这里所做的事似乎很愚蠢,但这并不能使问题变得无效。 – cjbarth 2013-02-04 17:51:05