In most Websites, you can see some pages open without logging in but some pages require the user to login to open it.

The pages which require a user to login will not open -- the system flow is that it first sends you to the Login page, followed by the page of your choice and then it will open. To achieve this requires extra coding and the logic to achieve it.

Example

In my Website, I have four pages:

Page Name Login Required
Yes / No
Description
• About MySelf No Display My information and this page does not require login.
• My Friends Yes This page will display my friend list and friend contact details This page requires login before opening.
• Coaching No Display my subject and topic which I teach and this page does not require login.
• Login No Login page to logged in.

Question/ Requirement / Task

In this scenario, when the user directly clicks on MyFriends, the system will redirect you to the login page, because the system requires a logged in user. After successful login, the system should open MyFriends page automatically.

Logical Answer

To achieve this,

  1. Check if the user is logged in or not in FriendList.aspx page.
    1. if (string.IsNullOrEmpty(Convert.ToString(Session["userid"])))
    2. {
    3. Response.Redirect("login.aspx?url=" + Server.UrlEncode(Request.Url.AbsoluteUri));
    4. }
    Server.UrlEncode(Request.Url.AbsoluteUri)
    (This is the line of code having information for which the page is requested.)

    Note: In the code, given above, we are redirecting the user to login.aspx page with the URL query string with the value of the clicked page.

  2. In Login.aspx, when the user successfully logs in, we have to check the URL and redirect to the clicked page.
    1. string ReturnUrl = Convert.ToString(Request.QueryString["url"]);
    2. if (!string.IsNullOrEmpty(ReturnUrl))
    3. {
    4. Response.Redirect(ReturnUrl);
    5. }
    6. else
    7. {
    8. Response.Redirect("aboutmyself.aspx?msgs=" + "SuccessLogin");
    9. }

Note In the code, given above, we are checking for URL query string value, if there is a value, followed by redirecting to the specific page; otherwise, aboutmyself.aspx.

Now, we will implement the above step by step.

Output

By default AboutMySelf.aspx opens, as shown below:

OutPut

Now, the user clicks My Friend menu option, shown below:

OutPut

Now, the user is redirected to Login.aspx page.

You can see the image, given below:

OutPut

You will see the address bar or URL of the page, http://localhost:8813/login.aspx?url=http%3a%2f%2flocalhost%3a8813%2fFriendList.aspx

The URL embedded above with the query string named URL is having the path of FriendList.aspx.

Afterwards, enter the User Name and Password. I checked the values in the backend code.

code

You will see in the image, given above, where ReturnUrl value is : http://localhost:8813/FriendList.aspx.

Display FriendList.aspx

Display

Step by Step to achieve our task: