Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing HttpApplication.Application variables from a class

I set up various global parameters in Global.asax, as such:

Application["PagePolicies"] = "~/Lab/Policies.aspx";
Application["PageShare"] = "/Share.aspx";
Application["FileSearchQueries"] = Server.MapPath("~/Resources/SearchQueries.xml");
...

I have no problem accessing these variables form .ascx.cs or .aspx.cs file -- ie. files that are part of the Web content. However, I can't seem to access 'Application' from basic class objects (ie. standalone .cs files). I read somewhere to use a slight variations in .cs files, as follows, but it always comes throws an exception when in use:

String file = (String)System.Web.HttpContext.Current.Application["FileSearchQueries"];
like image 853
Testing123 Avatar asked Jun 09 '10 23:06

Testing123


2 Answers

While it's true that you can use HttpContext.Current from any class you must still be processing an HTTP request when you call it - otherwise there is no current context. I presume that's the reason you're getting an exception, but posting the actual exception would help clarify matters.

like image 192
EMP Avatar answered Oct 01 '22 01:10

EMP


to share your variable across app, and to be able to access it from standalone class, you can use static variable of a class, instead of using HttpApplication variable.

public MyClass{
 public static int sharedVar;
}

//and than you can write somwhere in app:
MyClass.sharedVar= 1;

//and in another location:
int localVar = MyClass.sharedVar;
like image 23
Yossi Avatar answered Oct 01 '22 01:10

Yossi