user3345212
user3345212

Reputation: 131

ASP.Net UrlReferrer Error

I have the following code:

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.UrlReferrer.Host != "www.test.com")
            {
                Response.Redirect("~/redirect.aspx");
            }
        }

My goal is, that page cannot be accessible if it is visited from a URL other than the one in the if statement however when I run my project I am getting the following error: An exception of type 'System.NullReferenceException' occurred

Why there is a NUll exception? if it is null it should just execute my code that Ihave inside Page_Load... Please advise if there is another way to do what I am attempting, or if there is a way I can handle the Null Exception Error. Thank you.

Upvotes: 0

Views: 701

Answers (1)

ntl
ntl

Reputation: 1299

Request.UrlReferrer can be null when there is no referrer, for example when you open this page directly in browser (as first page), or do request manually from fiddler etc. So, you should check if Request.UrlReferrer != null first or handle case when Request.UrlReferrer is null.

In your case you may try:

protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.UrlReferrer == null || Request.UrlReferrer.Host != "www.test.com")
            {
                Response.Redirect("~/redirect.aspx");
            }
        }

This code will check if your page was requested from www.test.com and was not accessed directly as first page without referrer.

Upvotes: 1

Related Questions