2016-07-05 58 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