代码之家  ›  专栏  ›  技术社区  ›  minty

如何从其他页面的代码隐藏中的global.asax访问属性

  •  13
  • minty  · 技术社区  · 17 年前

    假设我在global.asax中定义了一个属性。

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

    我想在另一页中使用该值。我怎么说呢?

    8 回复  |  直到 17 年前
        1
  •  19
  •   Panos    17 年前

    您可以这样访问该类:

    ((Global)this.Context.ApplicationInstance).Roles
    
        2
  •  3
  •   Jon Skeet    17 年前

    在我看来,这只取决于会话,所以为什么不让它成为一对以会话为参数的静态方法呢?然后可以从页面中传入“Session”属性的值。(任何 当然,有权访问HttpApplication的用户只能引用其会话属性。)

        3
  •  2
  •   Eoin Campbell    17 年前

    如果这是您需要在所有页面中访问的属性,那么最好定义一个所有其他页面都要扩展的基本页面。。。

    e、 g.默认情况下

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

    您可以做的是将BasePage.cs添加到您的应用程序代码文件夹中

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

    然后让你的页面扩展这个。

    public partial class _Default : BasePage
    {
    }
    
        4
  •  1
  •   Will Will    17 年前

    要访问全局类中定义的属性,请使用以下任一选项:

    • HttpApplication和Page类中定义的应用程序属性(例如Page.Application[“TestItem”])

    • HttpContext.ApplicationInstance属性(例如HttpContext.Current.ApplicationInstance)

    使用这两种方法之一,可以将结果强制转换为全局类型并访问所需的属性。

        5
  •  1
  •   B Faley    15 年前

    您还可以使用以下语法:

    ((Global)HttpContext.Current.ApplicationInstance).Roles
    
        6
  •  0
  •   Chris Pietschmann    17 年前

    如果值依赖于会话,那么使用HttpContext.Items字典实际上很简单:

    将此代码放在Global.asax中以存储值:

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

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

    下面是一个详细介绍它的链接: http://aspnet.4guysfromrolla.com/articles/060904-1.aspx

        7
  •  0
  •   Marc    16 年前

    在.NET3.5的global.asax本身上,我使用了typeof(global_asax),效果很好。实际上,让我来到这里的是实现dotnetopenid示例。我改变了其中的一些以使用应用程序缓存,就像威尔建议的那样。

        8
  •  0
  •   Daniel B    13 年前

    对于无法将全局作为一个类的项目的其他层:

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

    只是我必须确保全局类中的Roles属性永远不会改变。