Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register handlers for application events in ASP.NET 5

If I wanted to handle application events in my ASP.NET app, I would register a handler in my Global.asax:

protected void Application_BeginRequest(object sender, EventArgs e)
{ ... }

Global.asax has been removed from ASP.NET 5. How do I handle such events now?

like image 352
Mister Epic Avatar asked Jul 20 '15 12:07

Mister Epic


1 Answers

The way to run some logic for each request in ASP.NET 5 is through Middlewares. Here is a sample middleware:

public class FooMiddleware
{
    private readonly RequestDelegate _next;

    public FooMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        // this will run per each request
        // do your stuff and call next middleware inside the chain.

        return _next.Invoke(context);
    }
}

You can then register this in your Startup class:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseMiddleware<FooMiddleware>();
    }
}

See here for more information on Middlewares in ASP.NET 5.

For any application start level invocations, see application startup documentation.

like image 189
tugberk Avatar answered Nov 20 '22 03:11

tugberk