Bhav
Bhav

Reputation: 2207

Ensure page is accessed from a specific link

Say if I have link1.aspx and link2.aspx. Within link1.aspx, I redirect the user to link2.aspx.

What is the most efficient way of checking that link2.aspx is only accessed via link1.aspx?

For example, something like:

link2.aspx:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        if page is not accessed via link1.aspx
        {
            Response.Redirect("~/portal.aspx");
        }
    }
}

I could use a query string but are there any other ways?

Upvotes: 2

Views: 61

Answers (2)

Win
Win

Reputation: 62290

You can use UrlReferrer. However, it is not a secure way of detecting where the user comes from.

For example,

if (string.Equals(Request.UrlReferrer.AbsoluteUri,
    "YOUR_REFERRER_URL",
    StringComparison.InvariantCultureIgnoreCase))
{

}

If it is redirecting between pages inside your application, I would like to suggest to use SessionState which is more secure and robust than UrlReferrer.

link1.aspx.cs

private bool IsValidUrl
{
    set { Session["IsValidUrl"] = true; }
}

protected void Button1_Click(object sender, EventArgs e)
{
    IsValidUrl = true;
    Response.Redirect("link2.aspx");
}

link2.aspx.cs

private bool IsValidUrl
{
    get
    {
        if (Session["IsValidUrl"] != null)
            return Convert.ToBoolean(Session["IsValidUrl"]);
        return false;
    }
    set { Session["IsValidUrl"] = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (IsValidUrl)
    {
        // user comes from valid url. 
        // .... Do somthing

        // Reset session state value
        IsValidUrl = false;
    }
}

Upvotes: 4

Claudio Redi
Claudio Redi

Reputation: 68440

You could use the Request.UrlReferrer property to check what page the user is coming from.

Upvotes: 3

Related Questions