首次尝试将Windows API中的WebAPI托管崩溃 [英] Hosting WebAPI in Windows-Service crashes on first attempt

查看:41
本文介绍了首次尝试将Windows API中的WebAPI托管崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有托管WebAPI(HttpSelfHostServer)的控制台应用程序.

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

在控制台应用程序中,我具有从SQL Server查询数据的控制器.

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

控制台应用程序可以正常工作(来自提琴手和Windows_client)现在,我想在Windows服务中托管WebAPI(HttpSelfHostServer).

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

因此,我创建了一个Service-Project,并在console-app-dll中引用了Controllers,以便可以找到控制器.

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

为了使调试的机会降到最低,我在Windows服务的事件日志中写了一些信息.

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

我可以毫无问题地启动和停止Windows服务.似乎httpselfhost已启动并处于活动状态.

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

问题:-首次尝试访问该网址时,服务会因以下原因而严重崩溃:

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.

我认为,windows服务中的自主机启动有效,并且主机也是可访问的(因为它在首次访问时崩溃).

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..

由于console-app可以正常工作,因此我仅在Windows服务中发布以下代码: Windows服务代码:

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

我正在使用VS2013,VB.NET和Win 8.1.

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

已安装.net RunTime,已安装所有实际更新.

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

任何帮助将不胜感激

非常感谢您的第一个快速解答

弗雷迪

推荐答案

回答得很晚,但仍然认为这可能对您有用.

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.

使用服务器作为新的HttpSelfHostServer(config)

这篇关于首次尝试将Windows API中的WebAPI托管崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆