Search code examples
asp.netasp.net-coreusing

How can I wrap an Asp.NET 4.5 request in a using { ... } statement?


To better explain what I would like to do in Asp.NET 4.5, I'll give an example of how I've gotten this to work in .NET Core.

In .NET Core, if you want all the code for a request to use a single object that gets disposed of if an Exception is thrown, you can create a middleware with the app.Use() method in the Startup class like the following:

app.Use(async delegate (HttpContext Context, Func<Task> Next)
{
    using (var TheStream = new MemoryStream())
    {
        //the statement "await Next();" lets other middlewares run while the MemoryStream is alive.
        //if an Exception is thrown while the other middlewares are being run,
        //then the MemoryStream will be properly disposed
        await Next();
    }
});

How can I do something like this in .NET 4.5? I was thinking of using the Global.asax.cs but I would have to span the using { ... } statement across all the various events (Application_Start, Application_AuthenticateRequest, etc), which I don't believe is possible.


Solution

  • I was thinking of using the Global.asax.cs

    Yes, using some pair of events like HttpApplication.BeginRequest with HttpApplication.EndRequest is the way to do this on ASP.NET pre-Core.

    but I would have to span the using { ... } statement across all the various events

    Yes-ish. What you need to do is split the using logic across those events. E.g., in the BeginRequest event, do the new MemoryStream() and store it in the request context. Then in the EndRequest event, retrieve the MemoryStream from the request context and call Dispose.