0

我有一个可用的 Web api 服务,我从一个控制台项目开始。现在我想让它作为服务运行。

我使用带有此代码的 installutil.exe 将其安装为服务:

[RunInstaller(true)]
 public    class ApplicationInstaller:Installer
{
    private ServiceProcessInstaller processInstaller;
    private ServiceInstaller serviceInstaller;

    public ApplicationInstaller()
    {

        serviceInstaller = new ServiceInstaller();
        processInstaller = new ServiceProcessInstaller();
        processInstaller.Account = ServiceAccount.LocalSystem;

        serviceInstaller.StartType = ServiceStartMode.Automatic;
        serviceInstaller.ServiceName = "WTT Rumsa";
        serviceInstaller.Description = "Web API for WTT Rumsa";

        Installers.Add(serviceInstaller);
        Installers.Add(processInstaller);


    }



}

这是我用来启动服务的:

     public static void StartService()
    {
        var startOptions = new StartOptions();
        var internalURL = $"http://{Environment.MachineName}:6666";
        startOptions.Urls.Add(internalURL);
        _logger.Debug($"Service started at: {internalURL}");

        startOptions.Urls.Add("http://localhost:6666");


        foreach(var address in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
        {
            if(address.AddressFamily==AddressFamily.InterNetwork)
            {
                var ipURL = $"http://{address.ToString()}:6666";

                _logger.Debug($"Service started at: {ipURL}");

                startOptions.Urls.Add(ipURL);


            }
        }

        using(WebApp.Start<SelfHostConfiguration>(startOptions))
        {
            Console.WriteLine($"Service started and listening at {internalURL}");
            Console.ReadLine();
        }
    }

当我启动服务时,我的记录器显示它一直通过 StartService() 运行。我可以看到我已经添加了我在客户端中调用的 ip。该服务在我启动后并没有停止。

但是,当我连接时,我收到此消息:“无法建立连接,因为目标机器主动拒绝了它”

由于帐户类型是 ServiceAccount.LocalSystem 并且它确实启动(并且不会引发异常),因此权限应该没问题。我已经为我使用的端口添加了一个例外到我的本地防火墙。

还有什么可能是错的?

编辑:在命令窗口中运行 netstat -ano,Web 服务作为控制台和服务运行,当它作为服务运行时,它不会显示在列表中,而作为控制台应用程序运行时它会显示。防火墙配置问题?

4

2 回答 2

2

Ok. I've found the solution (or the problems) First of all: when running a console app as a service the compiler skips the Console.WriteLine and Console.ReadLine (I guess the entire Console type is just ignored)

This means that the program will step out of my using statement:

    using(WebApp.Start<SelfHostConfiguration>(startOptions))
    {
        Console.WriteLine($"Service started and listening at {internalURL}");
        Console.ReadLine();
    }

And that is obviously bad since the server is disposed. What made it difficult to debug was the fact that the service does not exit until stopped, even without the Console.ReadLine. If it were a normal Console application it would have exited. So the solution was just to start the service like this:

_webapp = WebApp.Start<SelfHostConfiguration>("http://+:8080");

于 2016-07-06T06:17:06.253 回答
1

您需要使用 ServiceBase.Run(...) 并实现一个 ServiceBase 类。ServiceBase.Run(...) 是一个阻塞调用,直到它收到来自 Windows 服务主机的停止。这里的例子。

于 2016-07-08T14:45:36.117 回答