如何在using{..}语句中包装Asp.NET 4.5请求



为了更好地解释我想在Asp.NET 4.5中做什么,我将举一个如何在.NET Core中使用它的例子。

在.NET Core中,如果您希望请求的所有代码都使用一个对象,而该对象在抛出异常时会被处理,那么您可以使用该应用程序创建中间件。在Startup类中使用((方法,如下所示:

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();
}
});

如何在.NET 4.5中执行类似的操作?我曾考虑使用Global.asax.cs,但我必须将using{…}语句跨越所有各种事件(Application_Start、Application_AuthenticateRequest等(,我认为这是不可能的。

我想使用Global.asax.cs

是的,在ASP.NET pre-Core上使用像HttpApplication.BeginRequestHttpApplication.EndRequest这样的事件对是实现这一点的方法。

但我必须将using{…}语句跨越所有不同的事件

是的。您需要做的是将using逻辑拆分到这些事件中。例如,在BeginRequest事件中,执行new MemoryStream()并将其存储在请求上下文中。然后在EndRequest事件中,从请求上下文中检索MemoryStream并调用Dispose

最新更新