Do you know how to migrate Global.asax to ASP.NET Core?

Last updated by Brady Stroud [SSW] about 1 month ago.See history

The Global.asax is an optional file that dictates how an ASP.NET application handles application, session and request events. The code for handling those events is written in Global.asax.cs, and when migrating to ASP.NET Core this code will need to be restructured.

Application Events

The methods given below are automatically linked to event handlers on the HttpApplication class at runtime.

The Application_Start() or Application_OnStart() method is called once upon the first request being received by the server, and is typically used to initialize static values. The logic for this starting method should be included at the beginning of Program.cs in the ASP.NET Core project.

The Application_Init() method is called after all event handler modules have been added. Its logic can be migrated by registering the logic with the WebApplication.Lifetime property ApplicationStarted.

The Application_End() and Application_Disposed() methods are fired upon application termination. They can be migrated by registering the logic with the WebApplication.Lifetime properties ApplicationStopping and ApplicationStopped.

Therefore, the following Global.asax.cs snippet would migrate as per the figures below.

public class MvcApplication : HttpApplication
{
    protected void Application_Start() {
        Console.WriteLine("Start");
    }

    protected void Application_Init() {
        Console.WriteLine("Init");
    }

    protected void Application_Stopping() {
        Console.WriteLine("Stopping");
    }

    protected void Application_Stopped() {
        Console.WriteLine("Stopped");
    }
}

Figure: Basic example application code from a Global.asax.cs file.

Console.WriteLine("Start");

var builder = WebApplication.CreateBuilder(args);
// ...
var app = builder.Build();
app.Lifetime.ApplicationStarted.Register(() => Console.WriteLine("Init"));
app.Lifetime.ApplicationStopping.Register(() => Console.WriteLine("Stopping"));
app.Lifetime.ApplicationStopped.Register(() => Console.WriteLine("Stopped"));

Figure: The above code migrated to ASP.NET Core.

Session Events

The Session_Start() is called when a new user session is detected. The Session_Start() method can be replaced using middleware that determines if a pre-set session variable was previously set. Additional approaches for replacing Session_Start() can be found in this StackOverflow thread.

Session_End() is called when a user session is ended, typically by timeout. There is no equivalent functionality for Session_End() in ASP.NET Core, and the any session management logic will need to be refactored to account for this.

Request Lifecycle Methods

The events raised during a request are documented in the HttpApplication API. The logic to be executed before and after a request should be implemented using middleware.

public class MvcApplication : HttpApplication
{
    protected void Application_BeginRequest() {
        Console.WriteLine("Begin request");
    }

    protected void Application_EndRequest() {
        Console.WriteLine("End request");
    }
}

Figure: Basic example request lifecycle code from a Global.asax.cs file.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.Use(async (context, next) =>
{
    Console.WriteLine("Begin request");
    await next.Invoke();
    Console.WriteLine("End request");
})

Figure: Using middleware to execute logic before and after a request.

Error Handling

Global error handling logic in Application_Error() method should be migrated to use middleware registered with the UseExceptionHandler() method.

public class MvcApplication : HttpApplication
{
    protected void Application_Error(object sender, EventArgs e) {
        var error = Server.GetLastError();
        Console.WriteLine("Error was: " + error.ToString());
    }
}

Figure: Basic example error handling code from a Global.asax.cs file.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseExceptionHandler(exceptionHandlerApp =>
{
    exceptionHandlerApp.Run(async context =>
    {
        var handlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
        var error = handlerPathFeature.Error;
        Console.WriteLine("Error was: " + error.ToString());

        // NOTE: context.Response allows you to set the returned status code
        // and response contents.
    })
});

Figure: Using exception handling middleware.

See here for more options for handling errors in ASP.NET Core.

Nick Curran
We open source. Powered by GitHub