ASP.NET Core使用TopShelf部署Windows服务

asp.net core很大的方便了跨平台的开发者,linux的开发者可使用apache和nginx来作反向代理,windows上能够用IIS进行反向代理。
反向代理能够提供不少特性,当然很好。可是还有复杂性,咱们也可使用windows service来直接启动kestrel。linux

asp.net core官方网站提供了一种基于windows服务部署的方法:在 Windows 服务中托管 ASP.NET Core
这种方式须要修改代码,而后部署的时候,使用命令行建立、安装服务,而后再启动。nginx

感受仍是不够爽快,咱们可使用topshelf改造一下。shell

TopShelf

topshelf能够很便捷地将一个windows console程序改形成windows service,只须要稍微修改一下代码结构,而后经过nuget包就能够简单操做了。安装与部署也是极其方便,并且,topshelf在调试的时候,直接是做为console程序,极其便于调试。apache

TopShelf项目地址:http://topshelf-project.com/json

步骤

首先引用nuget包:c#

Install-Package TopShelf

而后改造一下program.cswindows

public class Program
{
    public static void Main(string[] args)
    {
        var rc = HostFactory.Run(x =>                                   //1
        {
            x.Service<MainService>(s =>                                   //2
            {
                s.ConstructUsing(name => new MainService(args));                //3
                s.WhenStarted(tc => tc.Start());                         //4
                s.WhenStopped(tc => tc.Stop());                          //5
            });
            x.RunAsLocalSystem();                                       //6

            x.SetDescription("JwtAPIService");                   //7
            x.SetDisplayName("JwtAPIService");                                  //8
            x.SetServiceName("JwtAPIService");                                  //9
        });                                                             //10

        var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());  //11
        Environment.ExitCode = exitCode;

        //CreateWebHostBuilder(args).Build().RunAsService();
    }
}

这里指定服务程序的内容在MainService这个类里面,并经过代码指定了服务的名称和描述等行为。之前的启动CreateWebHostBuilder方法转移到了这个类中:app

public class MainService
{
    private string[] args;
    public MainService(string[] vs)
    {
        args = vs;
    }
    public void Start()
    {
        var isService = !(Debugger.IsAttached || args.Contains("--console"));
        var builder = CreateWebHostBuilder(args.Where(arg => arg != "--console").ToArray());

        if (isService)
        {
            var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
            var pathToContentRoot = Path.GetDirectoryName(pathToExe);
            builder.UseContentRoot(pathToContentRoot);
        }

        var host = builder.Build();
        host.Run();
    }

    public void Stop()
    {
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        var config = new ConfigurationBuilder()
// .SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json", optional: true, reloadOnChange: true)
.Build();

        return WebHost.CreateDefaultBuilder(args)
                .UseKestrel()
                .UseConfiguration(config)
                .UseStartup<Startup>();
    }
}

Start方法指定服务启动时,服务的执行不须要依赖于Microsoft.AspNetCore.Hosting.WindowsServices这个nuget包。
另外Contentroot须要注意,使用windows服务进行提供服务,GetCurrentDirectory的根目录是system32,而不是asp.net core的dll的目录。使用appsettings.json时,可能会引发问题,最好使用自定义的程序配置(例如这里经过config.json进行设置)。框架

运行

  • 肯定是否存在 Windows 运行时标识符 (RID),或将其添加到包含目标框架的 中:
<PropertyGroup>
   <TargetFramework>netcoreapp2.1</TargetFramework>
   <RuntimeIdentifier>win7-x64</RuntimeIdentifier>
</PropertyGroup>
  • 发布,最终能够获得可执行程序。直接双击运行,程序就能够以console的形式启动,方便调试。
  • 命令行运行xxxx.exe install就而能够安装服务,而后服务就能够自动启动。
  • 命令行运行xxxx.exe uninstall就能够卸载服务。整个过程不须要新建用户与策略。

后记

吐槽:直接使用TopShelf,调试windows服务的过程变得不那么痛苦了,想起附加调试器的过程,简直了。
P.S. 须要最新版本的topshelf才能够支持asp.net core的服务部署。asp.net

相关文章
相关标签/搜索