开发者

ASP.NET Application Lifecycle - how to check configuration properties exist?

开发者 https://www.devze.com 2023-02-13 04:17 出处:网络
I\'ve written a singleton class that exposes the web.config properties in a nice get property kind of way.

I've written a singleton class that exposes the web.config properties in a nice get property kind of way.

I want a Load method to parse the data in the config and set the public properties, and I want to throw exceptions (so they are logged in the EventLog) when a configurat开发者_JS百科ion key is missing or can't be parsed.

I tried placing the Load() code in Application_Start of the global.asax but then remembered this will only be run once, or until the application restarts.

Where is the best place to put code that you need to run 'everytime' your site is started/run by the user? I basically want the website to stop functioning if certain config properties cannot be loaded.

Thanks.


When you change your web.config file, the application pool is recycled. This means that the next hit will cause your Application_Start method to be called.

Altering the following files will also trigger an immediate restart of the application pool:

- web.config
- machine.config
- global.asax
- Anything in the bin directory or it's sub-directories

On that basis, as soon as your configuration is changed, it will be reloaded the next time a user hits the site, which should resolve the problem with the minimum number of configuration reloads, as opposed to reloading whenever a session starts for example. Therefore, you can do this (in your global.asax):

static bool configValid = false;
void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext context = base.Context;
    HttpResponse response = context.Response;
    HttpRequest request = context.Request;

    // Redirect users to an alternate page if the current config is invalid
    // I happen to pass the Url they were attempting to access in the query string
    // that way you can give them a "try again" link
    if ((!configValid) && (!request.Url.ToString().Contains("BadConfig.aspx")))
    {
        response.Redirect("BadConfig.aspx?originalUrl=" + context.Server.UrlEncode(request.Url.ToString()));
    }
}

void Application_Start(object sender, EventArgs e) 
{
    // Load config and determine if it's valid, thus setting configValid to true/false
    //
    //
    configValid = false;

}
0

精彩评论

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

关注公众号