Getting the HTTP Referrer in ASP.NET
I'm looking for a quick, easy and reliable way of getting the browser's HTTP Referrer in ASP.Net (C#). I know the HTTP Referrer itself is unreliable, but I do want a reliable way of getting the referrer if it is present.
Solution 1:
You could use the UrlReferrer property of the current request:
Request.UrlReferrer
This will read the Referer HTTP header from the request which may or may not be supplied by the client (user agent).
Solution 2:
Request.Headers["Referer"]
Explanation
The Request.UrlReferer
property will throw a System.UriFormatException
if the referer HTTP header is malformed (which can happen since it is not usually under your control).
Therefore, the Request.UrlReferer
property is not 100% reliable - it may contain data that cannot be parsed into a Uri
class. To ensure the value is always readable, use Request.Headers["Referrer"]
instead.
As for using Request.ServerVariables
as others here have suggested, per MSDN:
Request.ServerVariables Collection
The ServerVariables collection retrieves the values of predetermined environment variables and request header information.
Request.Headers Property
Gets a collection of HTTP headers.
Request.Headers
is a better choice than Request.ServerVariables
, since Request.ServerVariables
contains all of the environment variables as well as the headers, where Request.Headers
is a much shorter list that only contains the headers.
So the most reliable solution is to use the Request.Headers
collection to read the value directly. Do heed Microsoft's warnings about HTML encoding the value if you are going to display it on a form, though.