Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access a property created in global.asax.cs?

I'm reading two values from the web.config in the Application_Start of my Global.asax.cs. The string values from the web.config are assigned to their public properties, also defined in the Global.asax.cs .

How do I access the properties in the global.asax.cs file from another class, method, and namespace?

Update #1 This is more complicated than I thought (or maybe I'm just making it complicated). The class where I want to reference these properties in a plain ol' class library and I don't have access to httpcontext (or I don't know how to access it).

like image 701
Joe Avatar asked Feb 08 '12 17:02

Joe


People also ask

Where can I find global ASAX?

The Global. asax, also known as the ASP.NET application file, is located in the root directory of an ASP.NET application. This file contains code that is executed in response to application-level and session-level events raised by ASP.NET or by HTTP modules.

What is global ASAX Cs in MVC?

The Global. asax file is a special file that contains event handlers for ASP.NET application lifecycle events. The route table is created during the Application Start event. The file in Listing 1 contains the default Global. asax file for an ASP.NET MVC application.

How do I add global ASAX Cs to my website?

How to add global. asax file: Select Website >>Add New Item (or Project >> Add New Item if you're using the Visual Studio web project model) and choose the Global Application Class template. After you have added the global.


2 Answers

Cast the current application instance to your Global type and access the properties there.

var app = (Your.App.Namespace.Global)HttpContext.Current.ApplicationInstance;
var x = app.YourProperty;
like image 190
Greg B Avatar answered Sep 21 '22 03:09

Greg B


If the Global.asax.cs doesn't manipulate the values, then simply read the values from the web.config like you already do in global.asax.cs.

However, if the Global.asax.cs does manipulate the values, then you could write the values into the "Application" object.

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

        Application.Add("Foo", "Bar");

    }

Lastly, you can mark the property you want to expose from the Global as static.

    public static string Abc { get; set; }
    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

        Abc = "123";

    }
like image 31
Patrice Calvé Avatar answered Sep 21 '22 03:09

Patrice Calvé