Windows服务应用程序中自托管ASP.NET Web API的问题

问题描述:

我在网上看到了一些文章,描述了如何在Windows服务应用程序中自托管ASP.NET Web API(请参见此处).我已经在VB.NET中编写了一些简单的代码,以在服务启动时启动自我主机,并在服务停止时停止自身主机,例如:

I've seen some articles on the web describing how to self host an ASP.NET Web API in a Windows service application (see here and here). I've written some simple code in VB.NET to start the self host when the service starts and stop it when the service stops, like so:

Protected Overrides Sub OnStart(ByVal args() As String)
    Try
        ' init a new self host configuration using the base address
        _config = New HttpSelfHostConfiguration(New Uri("http://localhost:8080"))

        ' map the URLs into the config
        MapRoutes(_config)

        _server = New HttpSelfHostServer(_config)
        ' start the server and wait for requests
        _server.OpenAsync()

    Catch ex As Exception
        Throw
    End Try
End Sub

Protected Overrides Sub OnStop()
    Try
        _server.CloseAsync().Wait()
        _server.Dispose()
    Catch ex As Exception
        Throw
    End Try
End Sub
#End Region

Private Sub MapRoutes(ByVal config As HttpSelfHostConfiguration)

    ' add route mappings
    With config.Routes
        .MapHttpRoute("API Default", "api/{controller}/{id}", New With {.id = RouteParameter.Optional})
    End With
End Sub

我的简单控制器如下所示:

My simple controller looks like this:

Public Class ClassesController
    Inherits ApiController

    Private _classes As List(Of [Class]) = New List(Of [Class])()

    Public Sub New()

        With _classes
            .Add(New [Class]() With {.ID = 1, .Name = "Geometry"})
            .Add(New [Class]() With {.ID = 2, .Name = "English 101"})
            .Add(New [Class]() With {.ID = 3, .Name = "Psychology 101"})
            .Add(New [Class]() With {.ID = 4, .Name = "Chemistry 101"})
            .Add(New [Class]() With {.ID = 5, .Name = "Physical Education"})
            .Add(New [Class]() With {.ID = 6, .Name = "Study Hall"})
            .Add(New [Class]() With {.ID = 7, .Name = "Wood Shop"})

        End With
    End Sub

    <HttpGet()>
    Public Function GetAll() As HttpResponseMessage

        Dim resp As HttpResponseMessage = Request.CreateResponse(Of List(Of [Class]))(HttpStatusCode.OK, _classes)

        Return resp

    End Function

    <HttpGet()>
    Public Function GetOne(ByVal id As Integer) As HttpResponseMessage

        Dim theClass As [Class] = (From c As [Class] In _classes
                                  Where c.ID = id
                                  Select c).FirstOrDefault()

        If theClass Is Nothing Then
            Return Request.CreateResponse(Of String)(HttpStatusCode.NotFound, "The requested class could not be found.")
        End If

        Return Request.CreateResponse(Of [Class])(HttpStatusCode.OK, theClass)

    End Function
End Class

该服务可以毫无问题地进行编译,可以使用installutil进行安装,并且可以正常启动.但是,当我点击该URL时,该服务将崩溃,并在事件日志中留下以下内容:

The service compiles without a problem, installs using installutil and apparently starts just fine. However, when I hit the URL the service crashes and leaves the following in my event log:

应用程序:WebAPISelfHostPOC.exe框架版本:v4.0.30319说明:由于未处理的异常,进程已终止.异常信息:System.Runtime.CallbackException堆栈:在System.Runtime.Fx + AsyncThunk.UnhandledExceptionFrame(System.IAsyncResult)在System.Net.LazyAsyncResult.Complete(IntPtr)在System.Net.LazyAsyncResult.ProtectedInvokeCallback(System.Object,IntPtr),位于System.Net.ListenerAsyncResult.WaitCallback(UInt32,UInt32,System.Threading.NativeOverlapped *)在System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32,UInt32,System.Threading.NativeOverlapped *)

Application: WebAPISelfHostPOC.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.Runtime.CallbackException Stack: at System.Runtime.Fx+AsyncThunk.UnhandledExceptionFrame(System.IAsyncResult) at System.Net.LazyAsyncResult.Complete(IntPtr) at System.Net.LazyAsyncResult.ProtectedInvokeCallback(System.Object, IntPtr) at System.Net.ListenerAsyncResult.WaitCallback(UInt32, UInt32, System.Threading.NativeOverlapped*) at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)

还有

故障处理应用程序名称:WebAPISelfHostPOC.exe,版本:1.0.0.0,时间戳:0x50217b41错误的模块名称:KERNELBASE.dll,版本:6.1.7601.17651,时间戳:0x4e211319异常代码:0xe0434352故障偏移量:0x0000b9bc故障进程ID:0x2b58故障应用程序启动时间:0x01cd74dbf3f6b8a5错误的应用程序路径:C:\ Gravic \ Development \ WebAPISelfHostPOC \ WebAPISelfHostPOC \ bin \ Debug \ WebAPISelfHostPOC.exe错误的模块路径:C:\ Windows \ syswow64 \ KERNELBASE.dll报告ID:3e81d995-e0cf-11e1-b8b3-f80f41109bb9

Faulting application name: WebAPISelfHostPOC.exe, version: 1.0.0.0, time stamp: 0x50217b41 Faulting module name: KERNELBASE.dll, version: 6.1.7601.17651, time stamp: 0x4e211319 Exception code: 0xe0434352 Fault offset: 0x0000b9bc Faulting process id: 0x2b58 Faulting application start time: 0x01cd74dbf3f6b8a5 Faulting application path: C:\Gravic\Development\WebAPISelfHostPOC\WebAPISelfHostPOC\bin\Debug\WebAPISelfHostPOC.exe Faulting module path: C:\Windows\syswow64\KERNELBASE.dll Report Id: 3e81d995-e0cf-11e1-b8b3-f80f41109bb9

任何人都可以向我指出一些在Windows服务中运行Web API的示例代码,或者指出我在代码中可能做错的任何事情吗?

Can anyone either point me to some sample code that runs a Web API in a Windows Service or point out anything I may have done wrong in my code?

谢谢!

该问题原来是GAC中安装的一组旧程序集,这些旧程序集是从Web API的Beta版安装中遗留下来的.我能够使我的项目引用新的程序集,并且问题得以解决.

The problem turned out to be a set of old assemblies installed in the GAC that were left over from a beta installation of the Web API. I was able to get my project to reference the new assemblies, and the problem was resolved.