Hosting ASP.NET Core as Windows service

前端 未结 7 1078
孤街浪徒
孤街浪徒 2020-12-04 08:43

As I get it in RC2 there\'s a support for hosting applications within Windows Services. I tried to test it on a simple web api project (using .NET Framework 4.6.1).

相关标签:
7条回答
  • 2020-12-04 09:31

    Using the latest VS2015 Update 2 ASP.NET Core Web Application (.NET Framework) template and with the mods to Program.cs as below, it is working just fine when run as a service, stand-alone and in VS. Notice that the path to the directory containing wwwroot needs to be set when run as a service.

    So far, I really like this template and pattern. Can develop MVC6 code as usual in Visual Studio and then it deploys cleanly as a service. In fact, I noticed that when deploying a local instance of the service for testing that there is no need to delete/create service using sc.exe. Just stop the service, publish the code and restart the service and it'll pick up the new changes.

    public class Program
    {
        public static void Main(string[] args)
        {
            IWebHost host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();
    
            if (args.Contains("--windows-service"))
            {
                host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot("<directory-containing-wwwroot>")
                .UseIISIntegration()
                .UseStartup<Startup>()
                .UseUrls("http://+:5000")
                .Build();
    
                Startup.is_service = true;
                host.RunAsService();
            }
            else
            {
                host.Run();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题