c# - 在 ASP.NET 5 中注册应用程序事件的处理程序

标签 c# asp.net visual-studio asp.net-core

如果我想在我的 ASP.NET 应用程序中处理应用程序事件,我会在我的 Global.asax 中注册一个处理程序:

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

Global.asax 已从 ASP.NET 5 中删除。我现在如何处理此类事件?

最佳答案

在 ASP.NET 5 中为每个请求运行一些逻辑的方法是通过中间件。这是一个示例中间件:

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

然后您可以在您的 Startup 类中注册它:

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

请在此处查看 more information on Middlewares in ASP.NET 5 .

对于任何应用程序启动级别的调用,请参阅 application startup documentation .

关于c# - 在 ASP.NET 5 中注册应用程序事件的处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31517135/

相关文章:

asp.net - 如何在同一文件夹中混合 MVC View 和 ASPX 页面?

c# - 将大量 xml 数据写入文件的最佳方法?

c++ - 我有 Visual Studio 错误调试断言失败

c# - WPF MVVM 更改模型

c# - 参数绑定(bind) : What happens under the hood?

asp.net - 嵌套中继器错误: Object reference not set to an instance of an object

visual-studio - Visual Studio生成事件立即返回

c# - 使用不同 UI 语言的性能计数器

c# - System.Collections.Immutable 类型 : why no . 等于

c++ - 以堆栈状态为条件的 Visual Studio 断点