开发者

Initiate User Scope Class at Session Start

开发者 https://www.devze.com 2023-01-03 09:37 出处:网络
I want to initiate a class for each user at the start of the user\'s session so that a single class can be used throughout the user\'s session.I checked out this post but I\'m not sure where I should

I want to initiate a class for each user at the start of the user's session so that a single class can be used throughout the user's session. I checked out this post but I'm not sure where I should be placing this Sessionhandler class. Inside global.asax? How do I go about accomplish开发者_C百科ing this?


I take that you will be running a common piece of code for all authenticated users (may be timers as you have mentioned).

Please see if the following steps solves your problem.

1. Have the user initialisation code in Session_OnStart

E.g.,

protected void Session_OnStart()
{
    // Do user initialization here
    Session["useridentifier"] = id;
    Session["isAuthenticated"] = true;
}

2. Derive a BaseController from Controller class , so that all the other controllers that you develop shall inherit from BaseController (de coupling)

E.g.,

Public class BaseController : Controller
{
}

3. Have the Common methods that needs to be executed in the constructor

E.g.,

Public class BaseController : Controller
{
   public BaseController()
   {
     if((bool.Parse(Session["isAuthenticated"]))
     {
       // write the user specific code here.
     }
  }

Hope this helps.

Thanks , Vijay


The class itself can go anywhere, since it is static, you just need to make sure you have a using directive for the right namespace when your accessing it.

If you want to create an instance of some class and store it in the user's session (perhaps using this SessionHandler class), then you can do that work in the Session_OnStart() handler in Global.asax.cs:

protected void Session_OnStart()
{
    // Do your work here
}
0

精彩评论

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