2

Code below is placed in page_Load. How I should handle this to bypass UrlReferrer when you enter page directly first time and there is no referrer? What I am missing here?

    if (HttpContext.Current.Request.UrlReferrer.AbsoluteUri != null)
    {
        urlReferer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
    }
    else
    {
        urlReferer = "";
    }

6 Answers 6

5

Just check UrlReferrerfor null:

if (HttpContext.Current.Request.UrlReferrer != null 
    && HttpContext.Current.Request.UrlReferrer.AbsoluteUri != null)
{
     urlReferer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
}     
else     
{         
    urlReferer = "";     
} 
Sign up to request clarification or add additional context in comments.

1 Comment

When try to check for if(HttpContext.Current.Request.UrlReferrer.AbsoluteUri != Null) then throws the NullReferenceException - Object reference not set to an instance of an object so I can't use this syntax but checking for if (HttpContext.Current.Request.UrlReferrer != null ) is working in my code also placing it in (!IsPostBack) makes it even better.
3

Who says the client passed by the referrer in the HTTP request?

Check if UrlReferrer is null first

if (HttpContext.Current.Request.UrlReferrer != null)
    {
        urlReferer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
    }
    else
    {
        urlReferer = "";
    }

1 Comment

This will throw NullReferenceException if HttpContext.Current.Request.UrlReferrer.AbsoluteUri == null
2

Why not this way much cleaner than checking nulls

private void Page_Load()
{
    if (!IsPostBack)
    {
        if (HttpContext.Current.Request.UrlReferrer != null)
        {
            urlReferer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
        }
        else
        {
            urlReferer = "";
        }
    }
}

Comments

2

I believe you need to check if HttpContext.Current.Request.UrlReferrer != null.

Comments

0

If UrlReferrer is null, then the test to AbsolutUri will fail.

Try initially testing UrlReferrer for null, this will probably correct the issue.

Comments

0

Use your debugger. If you're running this out of visual studio, than you might be brought to a debugger window when the exception is thrown. There are multiple tabs at the bottom of the debugger including "Locals" and "Watch" you can use those to see what variables are being stored.

If the above code is indeed what's causing the problem than

HttpContext.Current.Request.UrlReferrer.AbsoluteUri
or
HttpContext.Current.Request.UrlReferrer
or
HttpContext.Current.Request
or
HttpContext.Current
or
HttpContext

is set to null

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.