ASP .Net Core Web API无法正确关闭

时间:2019-07-18 10:07:06

标签: c# asp.net-web-api .net-core

我正在linux上编写ASP .Net Core Web api,但无法使用CTRL + C关闭程序。
当我使用dotnet run从终端运行它时,则CTRL + C正常工作。但是我必须将其发布到文件夹中,并且当我使用./(name of program)运行发布的程序时,然后按CTRL + C后它会写成Application is shutting down...,但是它无法正确关闭,并且正在响应API调用。 / p>

我的API的Program.cs文件:

namespace UploaderWebApi
{
    public class UploaderWebApiHostService : IHostedService
    {
        private readonly IApplicationLifetime applifetime;
        public static Provider provider;

        public UploaderWebApiHostService(IApplicationLifetime applifetime)
        {
            this.applifetime = applifetime;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            applifetime.ApplicationStarted.Register(OnStarted);
            applifetime.ApplicationStopping.Register(OnStopping);
            applifetime.ApplicationStopped.Register(OnStopped);
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            throw new NotImplementedException();
        }

        private void OnStarted()
        {
            provider = new Provider();
            provider.Start();
        }

        private void OnStopping()
        {
        }

        private void OnStopped()
        {
        }
    }

    public class Program
    {
        public static int webapiport;

        public static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                webapiport = 11001;
            }
            else
            {
                webapiport = Convert.ToInt32(args[0]);
            }

            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services)=> services.AddHostedService<UploaderWebApiHostService>())
                .UseUrls($"http://*:{webapiport}")
                .UseStartup<Startup>()
        ;
    }
}

0 个答案:

没有答案