如何以编程方式重启asp.net核心应用程序?

ead*_*dam 31 asp.net-core

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

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

Moh*_*imi 30

.NET Core 2

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

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

    }
}
Run Code Online (Sandbox Code Playgroud)

资料来源:http://www.blakepell.com/asp-net-core-ability-to-restart-your-site-programatically-updated-for-2-0

  • 我不投票,因为 `ApplicationLifetime.StopApplication();` 只是停止应用程序,而不是重新启动它 (8认同)
  • 我尝试了这个,它停止了应用程序并且不会重新启动它(这是我所期望的,基于方法名称) (4认同)

Che*_*het 23

更新:Mirask的答案对于.NET Core 2更为正确.

在Program.cs中,您将看到对的调用host.Run().这种方法有一个接受a的重载System.Threading.CancellationToken.这就是我在做的事情:

public class Program {

    private static CancellationTokenSource cancelTokenSource = new System.Threading.CancellationTokenSource();

    public static void Main(string[] args) {

        var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

        host.Run(cancelTokenSource.Token);
    }

    public static void Shutdown() {
        cancelTokenSource.Cancel();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在我的控制器中,我可以调用Program.Shutdown(),几秒钟后应用程序就会死掉.如果它位于IIS后面,则另一个请求将自动启动该应用程序.

  • 小更新.我发现在.NET Core 2.0中我不再使用Run(token)方法.我使用以下代码来解决这个问题:.RunAsync(cancellationTokenSource.Token).GetAwaiter().GetResult(); (5认同)

WoI*_*IIe 15

ASP.NET 核心 3+

由于接受的答案是 using IApplicationLifetimewhich 在 ASP.NET Core 3 之后已过时,新的推荐方法是使用IHostApplicationLifetime位于Microsoft.Extensions.Hosting命名空间中的 which 。

在我的 Blazor 应用程序中,我可以使用以下代码:

@inject IHostApplicationLifetime AppLifetime

<button @onclick="() => AppLifetime.StopApplication()">Restart</button>
Run Code Online (Sandbox Code Playgroud)


Tar*_*aro 5

对于 .NET Core 2.2,您可以使用以下代码:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using System.Threading;

namespace BuildMonitor
{
    public class Program
    {
        private static CancellationTokenSource cancelTokenSource = new System.Threading.CancellationTokenSource();

        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();
            host.RunAsync(cancelTokenSource.Token).GetAwaiter().GetResult();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();

        public static void Shutdown()
        {
            cancelTokenSource.Cancel();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

例如,服务器关闭可以放置在某个网页后面:

using System;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace BuildMonitor.Pages
{
    public class StopServerModel : PageModel
    {
        public void OnGet()
        {
            Console.WriteLine("Forcing server shutdown.");
            Program.Shutdown();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

stopServer.bat 可以是这样的:

@echo off
rem curl http://localhost:5000/StopServer >nul 2>&1
powershell.exe -Command (new-object System.Net.WebClient).DownloadString('http://localhost:5000/StopServer') >nul
exit /b 0
Run Code Online (Sandbox Code Playgroud)


det*_*ode 5

上面的解决方案都没有达到我想要的效果。这就是我想出的:

 public class Program
{
    private static CancellationTokenSource cts = new CancellationTokenSource();
    private static string[] _args;
    private static bool _restartRequest;

    public static async Task Main(string[] args)
    {
        _args = args;

        await StartServer();
        while (_restartRequest)
        {
            _restartRequest = false;
            Console.WriteLine("Restarting App");
            await StartServer();
        }
    }

    public static void Restart()
    {
        _restartRequest = true;
        cts.Cancel();
    }

    private static async Task StartServer()
    {
        try
        {
            cts = new CancellationTokenSource();
            await CreateHostBuilder(_args).RunConsoleAsync(cts.Token);
        }
        catch (OperationCanceledException e)
        {
            Console.WriteLine(e);
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}
Run Code Online (Sandbox Code Playgroud)


Vic*_*aci 2

如果您仅需要这个用于开发场景,那么您可以使用dotnet-watch(对于 dotnet)或dnx-watch(对于 dnx)。

如果您希望应用程序在生产环境中重新启动,那么您必须实现类似于观察者所做的事情。您需要一个外部进程来终止并重新启动该进程。或者您需要您的应用程序启动其自身的实例,然后终止自身。不幸的是,没有任何现成的东西可以实现这一点。

  • 这将是一个黑客攻击,但应用程序可以以编程方式更改配置文件来触发应用程序重新启动吗? (5认同)