如何以编程方式重新启动asp.net核心应用程序? [英] How to restart asp.net core app programmatically?

查看:100
本文介绍了如何以编程方式重新启动asp.net核心应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以编程方式在asp.net core中重新启动应用程序?

How can I restart an app in asp.net core programmatically?

我想清除缓存并导致应用程序重新进入启动状态.

I want to clear cache and cause the application to re-enter the startup.

推荐答案

在阅读我的答案之前请仔细阅读问题,如果您理解的话,请对我的回答投反对票,不要不要因为不适合您或正在寻找其他东西而拒绝投票.此解决方案将停止该应用程序,并在下一个请求中使该应用程序重新进入启动状态".

Before you read my answer "please read the question carefully, if you understand it, then come and downvote on my answer, don't downvote just because it does not work for you or you are looking for something else. This solution is going to stop the app and cause the application to re-enter the startup in the next request".

.NET Core 2 有时候您可能希望强制ASP.Net Core 2网站以编程方式回收.即使在MVC/WebForms时代,这也不一定是推荐的做法,但是,有一种方法. ASP.Net Core 2允许注入IApplicationLifetime对象,使您可以做一些方便的事情.首先,它可以让您注册启动,关机和关机事件,类似于当天通过Global.asax进行的活动.但是,它还公开了一种方法,可让您关闭站点(无需黑客!).您需要将其注入您的网站,然后简单地调用它.以下是带有路由的控制器的示例,该路由将关闭站点.

.NET Core 2 There may come a time when you wish to force your ASP.Net Core 2 site to recycle programmatically. Even in MVC/WebForms days this wasn't necessarily a recommended practice but alas, there is a way. ASP.Net Core 2 allows for the injection of an IApplicationLifetime object that will let you do a few handy things. First, it will let you register events for Startup, Shutting Down and Shutdown similar to what might have been available via a Global.asax back in the day. But, it also exposes a method to allow you to shutdown the site (without a hack!). You'll need to inject this into your site, then simply call it. Below is an example of a controller with a route that will shutdown a site.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace MySite.Controllers
{
    public class WebServicesController : Controller
    {
        private IApplicationLifetime ApplicationLifetime { get; set; }

        public WebServicesController(IApplicationLifetime appLifetime)
        {
            ApplicationLifetime = appLifetime;
        }

        public async Task ShutdownSite()
        {
            ApplicationLifetime.StopApplication();
            return "Done";
        }

    }
}

来源: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆