Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check for login in every page

I've multiple web forms in my project. It is simple project. User authentication is done by checking valid username and password and role from database. In the Page_Load event for every web page I've added this code :

protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session["username"] == null & Session["role"] == null)
                {
                    Response.Redirect("WebLogin.aspx", false);
                    Context.ApplicationInstance.CompleteRequest();
                }
            }
            catch (Exception ex) { }
        }

so that if someone tries to go to a specific web page via URL, it will check for username and role. If it is null then redirect to login page.

Please can you suggest any other way of doing this, more efficient. It looks very unprofessional to add this code in every code behind page.

like image 314
user4221591 Avatar asked Dec 01 '16 05:12

user4221591


1 Answers

Create new class PageBase that inherits Page class and override the onload method for it then add you login check code

public abstract class PageBase : Page
{
    protected override void OnLoad(EventArgs e)
    {
        if (Session["username"] == null & Session["role"] == null)
            {
                Response.Redirect("WebLogin.aspx", false);
                Context.ApplicationInstance.CompleteRequest();
            }
        }

now for each of your forms just change the page class inheritance from this:

public partial class HomePage : Page

to PageBase like this:

public partial class HomePage : PageBase

This will make your code more organized and clean

like image 111
Monir Tarabishi Avatar answered Sep 30 '22 05:09

Monir Tarabishi