Problems Self-Hosting ASP.NET Web API in a Windows Service Application

好久不见. 提交于 2021-02-10 03:20:49

问题


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

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:

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*)

And

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

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?

Thanks!


回答1:


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.




回答2:


Is the account that you are running the service in a local administrator? Or did you assign permissions to allow access to the url?



来源:https://stackoverflow.com/questions/11854232/problems-self-hosting-asp-net-web-api-in-a-windows-service-application

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