开发者

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;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜