Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cache object in global.asax

Status
Not open for further replies.
Apr 11, 2002
193
IN
Hi,

I am using the cache object to store user permissions as i want these permissions in the global.asax. On successful login i store the permissions in the cache object. Suppose there are 2 users and first one logs in and gets inside the site then the second one logs in so will the permissions in the cache object be overwritten. If yes then what would be the solution for this.
I am using ASP.net 2.0 and C#. The permissions are stored as a string[]. I need them in global.asax because i want to authenticate user for every url(which i get using Context.Request.Path)

Thanks,
Manish
 
use Session not Cache

Cache = accessible to all users. lives for cache life cycle set by you
Application = accessible to all users (like cache). lives until the application shuts downs (server reset or all users log off).
Session = accessible by current user only. alive for the life of the current series of events. (disposed if user leaves website, closes browser or inactive for 20 minutes [can be changed])
ViewState = accessible by current user for current page only. alive through postbacks. reset when page is fully revisited.

because these object automatically clean up after themselves. your logic need to check if the values exist, if not reload them, then pass them along to the calling function.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Hi,

Thanks for the reply. But in global.asax we cannot access the session object. So how can we do it.

Thanks,
Manish
 
Hi,

If i write
string user = HttpContext.Current.Session["UserName"].ToString();
in the global.asax then i get a nullreferenceexception.

I am writing it in the Application_AuthenticateRequest event.

Thanks,
Manish
 
the code should look something like this.
Code:
public function GetCurrentUser()
{
   HttpContext c = HttpContext.Current;
   string userName = c.Session["UserName"];
   if (string.IsNullOrEmpty(userName))
   {
      //forms auth
      c.Response.Redirect("~/Login.aspx");

      //windows auth
      userName = System.Security.Principle.WindowsIndentity.GetCurrent().Name;
      c.Session["UserName"] = userName;
   }
   return userName;
}
to take this a step father. I would create an object to represent the user. when you request the object load your session data into the user object and have the calling code work against user object.

this way your gui code never directly accesses session. it access session via the user object.

session can be reset if IIS is restarted, the web.config is changed, you call Session.Abondon();, user leaves the website/closes browser.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Hi,

I tried a simple thing. I wrote

Session["UserName"] = "Manish"; on the page load of the Login page. Then in Application_AuthenticateRequest event i wrote
string url = Context.Request.Path;
if(!url.Contains("Login.aspx")
{
HttpContext c = HttpContext.Current;
string userName = string.Empty;
if(c.Session["UserName"] != null)
userName = c.Session["UserName"].ToString();
}

The control is going in when it passes the login so the session has a value. It still gives me NullReferenceException.

Thanks,
Manish
 
try this on your page load event:
Code:
Session["UserName"] = "Manish"; 
response.write(Session["UserName"]);
do you disable session on the page/app. if so it must be enabled to work properly.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Hi,

I tried it and i get the response written on the page.
Can you try in a test application to access a session variable. I think we cannont get session objects in Global.asax.

Thanks,
Manish
 
Hi,

Am i wrong.

I dont get a compile time error in Global.asax but when i run it i get the NullReferenceException. I have checked that the session is valid as i can print it on the page as you suggested.

As you suggested earlier, if i create a user object and create a property and assign the Session["UserName"] to the property. How long do you think this object will persist. Will it not be garbage collected. Correct me if i have misunderstood.

Please advice.

Thanks,
Manish
 
by default Session is alive for 20 minutes since the last request. because session exists across requests make sure you don't set Session["UserName"] == null or "".

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Hi,

I am not setting the session to null or "". In my web.config i have got <sessionState timeout="20" mode="InProc">

Thanks,
Manish
 
I've only used the default settings. try removing this line from the web.config and see if it works.

if it does the problem is either the timeout or mode. you'll need to research the different modes and determine which is best for your scenario.

it's common for time attributes to track milliseconds, not minutes. so 20 could be milliseconds which would explain why your session is null on postback.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Hi,

I did that and i still get the error.

This is what i have in the event
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id =
(FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;

string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);

string url = Context.Request.Path;

if (url.Contains(".aspx"))
{
System.Web.Caching.Cache cache = HttpContext.Current.Cache;
if (!url.Contains("Login.aspx"))
{
if (cache[Constants.SessionPermissionArrayVariable] != null)
{
HttpContext c = HttpContext.Current;
string userName = string.Empty;
if (c.Session["UserName"] != null)
userName = c.Session["UserName"].ToString();

string[] permissions = (string[])cache[Constants.SessionPermissionArrayVariable];
if (permissions != null)
{
string strValue = "~/ErrorPage.aspx";
string strRedirect = "<script language='javascript'>parent.main.location.href='" + strValue + "'<" + "/script>";

string errorMsg = string.Empty;
ADRControllerWS.Controller controller = new ADRControllerWS.Controller();
if (!controller.AuthorizeUserByURL(url, id.Name, permissions, out errorMsg))
{
//To-do call WS for logging
Response.Redirect("~/ErrorPage.aspx");
}

}
}
}
}
}
}
}

Currently i am storing the user permissions in a cache object which is nasty for me. Its ok now as i only have one user, but next week there will be many users.
On if(c.Session["UserName"] != null) i get the error.

This is very critical for me.

Thanks,
Manish
 
Hi,

If i create a singleton class and create a public static varible in it named permissions and after successful login i assign the variable the permissions(string[]). Then can i differenciate the static variable for different users.

Please advice.

Thanks,
Manish
 
Hi,

I got the solution. After successful login create a authentication ticket and assign permissions to it then you can get the permissions in the global.asax.

Thanks for your help.

Manish
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top