asp.net core mvc 里的application中的start,end等事件

我们以前在用asp.net mvc或者webform的时候,经常用用到Application里的事件 start,end等。我们在.net core 里也同样有类似的方法。

在Startup类里,Configure方法里添加一个参数IApplicationLifetime applicationLeftTime就可以了。具体写法如下:

  public void Configure(IApplicationBuilder app, IHostingEnvironment env,IApplicationLifetime applicationLeftTime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            applicationLeftTime.ApplicationStarted.Register(() =>
            {
                //里面可以写其他逻辑

                Console.Write("ApplicationStarted");
            });

            applicationLeftTime.ApplicationStopped.Register(()=> {
                //里面可以写其他逻辑
                Console.Write("ApplicationStopped");
            });

            applicationLeftTime.ApplicationStopping.Register(() => {
                //里面可以写其他逻辑
                Console.Write("ApplicationStopping");
            });



            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

 

你可能感兴趣的:(asp.net core mvc 里的application中的start,end等事件)