Hosting WebAPI in Windows-Service crashes on first attempt

匿名 (未验证) 提交于 2019-12-03 10:10:24

问题:

I have an console-app with hosted WebAPI (HttpSelfHostServer).

In the console-app I have Controllers that query data from SQL-Server.

The console-app works without problems (from fiddler and a Windows_client) Now I want to host the WebAPI (HttpSelfHostServer) in a Windows-Service.

Therefore I have created a Service-Project and referenced the Controllers in console-app-dll so that the controllers should be found.

To have a minimal chance to debug, I write some information in the event log from the windows service.

I can start and stop the windows-service without problems. It also seems as that the httpselfhost is started and active.

Problem: - By first attempt to the url, the service crashes hard with:

System.NullReferenceException (eventlog-entry to .net RunTime)   Anwendung: WS_MatrixGuide.exe Frameworkversion: v4.0.30319 Beschreibung: Der Prozess wurde aufgrund einer unbehandelten Ausnahme beendet. Ausnahmeinformationen: **System.NullReferenceException** Stapel:    bei System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__5(System.Object)    bei System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object)    bei System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)    bei System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)    bei System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()    bei System.Threading.ThreadPoolWorkQueue.Dispatch()    bei System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() 

I have tried for days to solve the problem, and I am desperate.

As I am not able to debug the service, I don't know where exactly the crash occurs.

I think, the start of the self-host in the windows-service works and the host also is reachable (as it crashes by first access).

So.. maybe I did something completely wrong in the service or I missed something important..

As the console-app works without problems, I post in the following only the code from the windows-service: Code to Windows-Service:

Imports System Imports System.ServiceProcess Imports System.ServiceModel Imports KA_MatrixGuide.Controllers ' Verweis auf Controller in KA_MatrixGuide (Konsolenanwendung) erstellen Imports System.Net.Mail Imports System.Web.Http.SelfHost ' Self Hosting Imports System.Web.Http Imports System.IO Public Class WS_MatrixGuide     Private SH As ServiceHost     Public Sub New()         InitializeComponent()         Me.ServiceName = "WS_MatrixGuide"     End Sub     Protected Overrides Sub OnStart(ByVal args() As String)         EventLog.WriteEntry("Vor SH = new...", System.Diagnostics.EventLogEntryType.Information)         SH = New ServiceHost(GetType(WS_MatrixGuide))         AddHandler SH.Faulted, AddressOf SH_Faulted        EventLog.WriteEntry("Vor Dim config...", System.Diagnostics.EventLogEntryType.Information)         Dim config As New HttpSelfHostConfiguration("http://127.0.0.1:21212")        EventLog.WriteEntry("Vor Config-Routes...", System.Diagnostics.EventLogEntryType.Information)         config.Routes.MapHttpRoute( _           name:="DefaultApi", _           routeTemplate:="api/{controller}/{id}", _           defaults:=New With {.id = RouteParameter.Optional} _         )         'Tracing-Info's in Event-Log schreiben...         EventLog.WriteEntry("Vor Using Server...", System.Diagnostics.EventLogEntryType.Information)         Using server As New HttpSelfHostServer(config)             ' Objekte zu Controllern erstellen (Interface für Zugriff)             Dim SQL_C As Type = GetType(KA_MatrixGuide.Controllers.SQLController)             Dim Beauty_C As Type = GetType(KA_MatrixGuide.Controllers.BeautyController)             Dim Freizeit_C As Type = GetType(KA_MatrixGuide.Controllers.FreizeitController)             Dim Gourmet_C As Type = GetType(KA_MatrixGuide.Controllers.GourmetController)             Dim Konfiguration_C As Type = GetType(KA_MatrixGuide.Controllers.KonfigurationController)             Dim Empfehlungen_C As Type = GetType(KA_MatrixGuide.Controllers.EmpfehlungenController)            Try                 EventLog.WriteEntry("Vor Server.OpenAsync...", System.Diagnostics.EventLogEntryType.Information)                 server.OpenAsync().Wait()                 EventLog.WriteEntry("Nach Server.OpenAsync...", System.Diagnostics.EventLogEntryType.Information)             Catch aggEx As AggregateException                 EventLog.WriteEntry("Fehler beim Laden des Servers (httpSelfHostServer)...", System.Diagnostics.EventLogEntryType.Information)             End Try             'Console.WriteLine()             'Console.WriteLine("Enter-Taste drücken, um die Konsolen-Anwendung zu beenden.")             'Console.ReadLine()             'AddHandler server.Faulted, AddressOf Server_Faulted ' => es gibt kein Server.Faulted         End Using         'EventLog.WriteEntry("WS_MatrixGuide wurde gestartet", System.Diagnostics.EventLogEntryType.Information)         EventLog.WriteEntry("Vor SH.Open...", System.Diagnostics.EventLogEntryType.Information)         SH.Open()         EventLog.WriteEntry("Nach SH.Open...", System.Diagnostics.EventLogEntryType.Information)     End Sub     Protected Overrides Sub OnStop()         Dim Infomeldung As String = "WS_MatrixGuide wurde gestoppt"         EventLog.WriteEntry(Infomeldung, System.Diagnostics.EventLogEntryType.Information)         SH.Close()         SH = Nothing     End Sub     Private Sub SH_Faulted() ' Eigener Fehlerhandler         Dim Fehlermeldung As String = "Fehler bei Ausführung von WS_MatrixGuide. Service wurde gestoppt"         EventLog.WriteEntry(Fehlermeldung, System.Diagnostics.EventLogEntryType.Error)        Dim cMsg As String = "Fehler bei der Ausführung von WS_MatrixGuide. Der Service wurde gestoppt."         Dim SMTPMail As New SmtpClient         SMTPMail.Host = "zrhms200"          SMTPMail.Port = 25 ' Standard-Port         Dim msg As New MailMessage         msg.From = New MailAddress("Service@matso.ch")          msg.To.Add("fredy.wenger@matso.ch")         msg.Subject = cMsg         msg.Body = cMsg         SMTPMail.Send(msg)     End Sub End Class 

I'm working with VS2013, VB.NET and Win 8.1.

The .net RunTime is installed, all actual updates are installed.

Any help will highly appreciated

Thanks a lot for a first fast answer

Fredy

回答1:

Answering very late to your answer, but still thought it might be useful to you.

You are hosting the server inside using, which will be disposed immediately after the method execution. Try to remove the below statement and that would resolve your problem.

Using server As New HttpSelfHostServer(config)



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!