2016-07-05 254 views
0

我有一个可用的web api服务,我从一个控制台项目开始。 现在我想让它作为服务运行。Owin selfhost asp.net 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时,webservice作为控制台和服务运行,当它作为服务运行时,它不会显示在列表中,并以控制台应用程序的形式运行。防火墙配置问题?

回答

0

好的。我已经找到了解决方案(或问题) 首先:当作为服务运行控制台应用程序时,编译器跳过Console.WriteLine和Console.ReadLine(我猜整个控制台类型只是被忽略)

这意味着,该方案将走出我的using语句:

​​

而这显然是不好的,因为服务器配置。 什么让它很难调试,即使没有Console.ReadLine,服务也不会退出直到停止。如果它是一个正常的控制台应用程序,它将退出。 因此,解决办法是刚刚开始这样的服务:

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

1

您需要使用ServiceBase.Run(...)并实现了ServiceBase类。 ServiceBase.Run(...)是一个阻塞调用,直到它从Windows服务主机收到停止。 示例here