Getting the HTTP Referrer in ASP.NET
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).
Request.Headers["Referer"]
Explanation
The Request.UrlReferrer
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.UrlReferrer
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["Referer"]
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.