Search code examples
c#asp.neturireferrer

get referrer from a specific page in same domain C#


My site has default.aspx page and you click submit and get to the customerinfo.aspx page. However,but they must come from the default.aspx page in the same domain. If the referrer is blank, an outside link, or their customer ID isn't there then it redirects back to the default.aspx page so they can enter their info, otherwise it displays the customer's data on the customerinfo.aspx page. Trying to prevent getting to the page from external URL and it shows object reference error if you do BUT just need to redirect to default page.

  Uri referrer = HttpContext.Current.Request.UrlReferrer;
        if (referrer == null || string.IsNullOrEmpty(Request.UrlReferrer.ToString()) && string.IsNullOrEmpty(Session["customerID"].ToString()))
        {
//This section is skipped because it's not a null referrer.
            Response.Redirect(url: "default.aspx", endResponse: false);
            return;
        }

        if (!IsPostBack)
        {

            if (!string.IsNullOrEmpty(Request.QueryString["customerID"]))
            {
                //This section is skipped even though there's a customer ID?
                Session["customerID"] = Request.QueryString["customerID"];
                customerInfo();
            }
            else
            {

                if (string.IsNullOrEmpty(Session["customerID"].ToString()))
                {
                    //This section is skipped because it's not an empty session, there's a customer ID.
                    Response.Redirect(url: "default.aspx", endResponse: false);
                }
                else
                {
                    //This section is hit because there's a customer ID so the string isn't empty but not sure why the first isn't hit?
                    customerInfo();
                }
            }
        }

Solution

  • I was able to figure it out. Took some parts of Albert's code and made some changes to mine.

          Uri referrer = HttpContext.Current.Request.UrlReferrer;
    
          string urlName = Request.UrlReferrer.ToString(); // grabbing referring page address        
          
            if (referrer == null && urlName != "default.aspx")
            {
                Response.Redirect(url: "default.aspx", endResponse: false);
                return;
            } 
    
            if (!IsPostBack)
            {
                if(Session["customerID"] == null && urlName != "default.aspx") //If both are false they go to homepage
                {
                    Response.Redirect(url: "default.aspx", endResponse: false);
                }
                else
                {
                    customerInfo(); //or else they get the customer info on the customer page
                }
            }