开发者

Login check in each ASP page using session variables (without forms/windows) authentication?

开发者 https://www.devze.com 2023-02-25 17:56 出处:网络
I am developing a website (as opposed to web application(so no global file)). I do not want to use forms/windows authentication or cookies. So session[] variables is the option i chose.

I am developing a website (as opposed to web application(so no global file)). I do not want to use forms/windows authentication or cookies. So session[] variables is the option i chose.

question:

How to check each and every page in the application if that session[] variable exists?

Any global class where the checking function can be included and called everyt开发者_开发技巧ime the page_load is executed?


Technically speaking, unless you're using the cookieless session state, session variables are made possible via cookies, so you're indirectly using them anyway ;)

Anyway, it's as simple as you stated. You can simply include some code to check the existence of a session variable in the page_load of each page:

if (Session["mySessionVar"] == null 
|| Session["mySessionVar"] IS_NOT_VALID) 
   Response.Redirect("/path/to/login/form/");

The IS_NOT_VALID represents some logic test to verify that the data in the variable is indeed valid data.

To have a "global class," you'll need to create a new page class that inherits from Page and does the check in your new classes Page_Load method. The trick is that every page you want to have checking the session variable will need to derive from your new class rather than the Page class. Pages that don't need the check can inherit from Page as normal. For example, something like this:

public class MyPageClass : Page
{
    protected override void OnLoad(EventArgs e)
    {
        // Check to see if the session is valid 
        // and redirect to login if not
        if (Session["mySessionVar"] == null 
        || Session["mySessionVar"] IS_NOT_VALID) 
            Response.Redirect("/path/to/login/form/");

        base.OnLoad(e);
    }
}

public partial class MyLoginRequiredPage : MyPageClass
{
    .
    .
    .
}


If you have a separate master page for home/profile page(different from login), you can write code in master page page_load only, so you don't have to write code for valid user in each page. Code:

if (Session["adminid"] == null || Session["adminid"].ToString() == "")
    {
        Response.Redirect("adminlogin.aspx");
    }

Even you can also use global.asax file as waqas raja told.

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号