3 out of 6 rated this helpful - Rate this topic

HttpRequest.UrlReferrer Property

Gets information about the URL of the client's previous request that linked to the current URL.

Namespace:  System.Web
Assembly:  System.Web (in System.Web.dll)
public Uri UrlReferrer { get; }

Property Value

Type: System.Uri
A Uri object.
Exception Condition
UriFormatException

The HTTP Referer request header is malformed and cannot be converted to a Uri object.

The following code example displays the value of two properties of the URL that referred the client to the current application.


Uri MyUrl = Request.UrlReferrer;
 Response.Write("Referrer URL Port: " + Server.HtmlEncode(MyUrl.Port.ToString()) + "<br>");
 Response.Write("Referrer URL Protocol: " + Server.HtmlEncode(MyUrl.Scheme) + "<br>");
   


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Safer coding response
If you don't have a referring page (e.g. coming from external site) then the Request.UrlReferrer object will be null. So yes, you need to check that the object exists before using the PathAndQuery property to avoid a null reference exception. This is a general coding consideration and not specific to this object.
Safer coding: Request.UrlReferrer
this is a precaution ... i'm not 100% sure that it's necessary.

   [NullReferenceException: Object reference not set to an instance of an object.]

The above exception appeared to have occurred with this code:

    if ((Request.UrlReferrer.PathAndQuery != null) && (Request.UrlReferrer.PathAndQuery != String.Empty))

removing the first occurrence of    .PathAndQuery    appears to have prevented the error:

    if ((Request.UrlReferrer            != null) && (Request.UrlReferrer.PathAndQuery != String.Empty))

i say "appears to have prevented the error" because imho the error should not have occurred in the first form; i could be wrong.

the complete c# code snippet follows, below.

regards ~~ gerry (lowry)



string guestReferrerUrl = "not detected"; //
string guestReferrerUrlAbsolutePath = "not detected"; //
string guestReferrerUrlQuery = "not detected"; //
if ((Request.UrlReferrer != null) && (Request.UrlReferrer.PathAndQuery != String.Empty))
{
    guestReferrerUrl = Request.UrlReferrer.AbsoluteUri;
    guestReferrerUrlAbsolutePath = Request.UrlReferrer.AbsolutePath;
    guestReferrerUrlQuery = Request.UrlReferrer.Query;
}