咱们对ASP.NET Core的使用已经进行了至关一段时间了,大多数时候,咱们的Web程序都是发布到Linux主机上的,固然了,偶尔也有需求要发布到Windows主机上,这样问题就来了,难道直接以控制台形式运行这个Web程序吗?windows
直接以控制台形式运行程序固然是能够的,但有如下问题:工具
若是咱们把程序以Windows服务的方式来运行,那以上这些问题都没有了。ui
微软官方有篇文章,关于如何作这个事情的:https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-2.1spa
我也主要是参考了这篇文章,但其中还有些小小的坑,本文将会提到。OK,Let's get down to work.命令行
生成目标固然选择最新的.NET Core 2.1了,包则须要引入Microsoft.AspNetCore.Hosting.WindowsServices,最新版是2.1.1(2018/6/19更新,不就是今天嘛),若是你尝试使用最新的2.1.1版,那会出问题,报依赖冲突,你根据报错内容把ASP.NET 2.1.0升级到ASP.NET 2.1.1去,但依旧会出现问题:debug
It was not possible to find any compatible framework version
The specified framework 'Microsoft.AspNetCore.All', version '2.1.1' was not found.调试
看来须要安装新的SDK才行,但微软官网最新的正式版SDK就是2.1.300啊,这个仍是等等吧,好,果断把版本降回2.1.0,这回没问题了。code
简单,很是简单,把Run改成RunAsService便可。blog
但这样会致使新的问题,你在开发过程当中调试程序的时候会出现这样的错误:Cannot start service from the command line or a debugger. A Windows Service must first be installed and then started with the ServerExplorer, Windows Services Administrative tool or the NET START command. 程序跑不起来,意思显而易见,因此咱们在调试中仍是要以普通的Run方式。因此改为这样:ci
IWebHost host = WebHost.CreateDefaultBuilder(args) .UseKestrel(options => { options.Listen(IPAddress.Any, 5201); }) //5201是我用的端口,你改为本身的 .UseStartup<Startup>() //使用Startup配置类 .Build(); bool isService = !(Debugger.IsAttached || args.Contains("--console")); //Debug状态或者程序参数中带有--console都表示普通运行方式而不是Windows服务运行方式 if (isService) { host.RunAsService(); } else { host.Run(); }
ASP.NET Core publish生成的目标中并不包含exe文件,因此按照官网文档去弄的话可能会卡住,这是正确的姿式:
sc create MyService binPath= "\"C:\program files\dotnet\dotnet.exe\" \"D:\Services\MyService.dll\"" DisplayName= "MyService" start= auto
注意1:必须以管理员身份运行上面命令
注意2:binPath参数、DisplayName参数及start参数的等号后面必须带一个空格(官网文档也特别提起了这点)
启动服务:
sc run MyService
中止服务:
sc stop MyService
卸载服务:
sc delete MyService
默认状况下,Windows系统服务是以system用户身份运行的,若是你须要切换身份运行,能够在“控制面板 - 管理工具 - 服务”中找到MyService,打开属性面板,在“登陆”Tab中指定特定身份。