简体   繁体   中英

How do I access properties from global.asax in some other page's code behind

Imagine I have a property defined in global.asax.

public List<string> Roles
{
    get
    {
        ...
    }
    set
    {
        ...
    }
}

I want to use the value in another page. how to I refer to it?

你可以像这样访问这个类:

((Global)this.Context.ApplicationInstance).Roles

It looks to me like that only depends on the session - so why not make it a pair of static methods which take the session as a parameter? Then you can pass in the value of the "Session" property from the page. (Anything which does have access to the HttpApplication can just reference its Session property, of course.)

If this is a property you need to access in all pages, you might be better defining a base page which all your other pages extend...

eg by default

public partial class _Default : System.Web.UI.Page 
{
}

What you could do is add a BasePage.cs to your App_Code folder

public class BasePage : System.Web.UI.Page 
{
   public List<string> Roles
   {
       get { ... }
       set { ... }
   }
}

And then have your pages extend this.

public partial class _Default : BasePage
{
}

Hey, I'm popping my stackoverflow.com cherry! My first answer after lurking for a month.

To access a property defined in your Global class, use either of the following:

  • the Application property defined in both the HttpApplication and Page classes (eg Page.Application["TestItem"])

  • the HttpContext.ApplicationInstance property (eg HttpContext.Current.ApplicationInstance)

With either of these, you can cast the result to your Global type and access the property you need.

您还可以使用以下语法:

((Global)HttpContext.Current.ApplicationInstance).Roles

For other layers of project which it is not possible to have Global as a class:

dynamic roles= ((dynamic)System.Web.HttpContext.Current.ApplicationInstance).Roles;
if (roles!= null){
   // my codes
}

Just I have to be sure the Roles property in Global class never changes. and another way is by reflection.

On the global.asax itself for .net 3.5 I used typeof(global_asax) and that worked fine. And, what actually lead me here was implementing the DotNet OpenID examples. I changed some of it to use the Application cache like Will suggested.

If the values are dependent on the Session then this is actually simple using the HttpContext.Items Dictionary:

Place this code in the Global.asax to store the value:

Dim someValue As Integer = 5
Context.Items.Add("dataKey", someValue)

Let retreive it in a Page with this code:

Dim someValue As Integer = CType(HttpContext.Current.Items("dataKey"), Integer)

Here's a link that describes it in further detail: http://aspnet.4guysfromrolla.com/articles/060904-1.aspx

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