简体   繁体   中英

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"];

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM