早上的人,
我有一个用vb.net和Application_Start
编写的Web API,我希望能够看到服务的运行位置(例如:http://localhost:57851)。这可能吗?
答案 0 :(得分:0)
这不适用于从VS启动的localhost应用程序,但在IIS托管应用程序时可以在生产环境中使用。
Friend Shared HostName As String = String.Empty
Friend Shared IPAddress As String = String.Empty
...
Shared Sub GetHostInfo()
' Get the sites section from the AppPool.config
Dim Section As Administration.ConfigurationSection = Administration.WebConfigurationManager.GetSection(Nothing, Nothing, "system.applicationHost/sites")
For Each Site As Administration.ConfigurationElement In Section.GetCollection
' Find the right Site in the collection...
If Site("name").ToString.Equals(HostingEnvironment.SiteName, StringComparison.OrdinalIgnoreCase) Then
' For each binding see if they are http based and return the port and protocol
For Each Binding As Administration.ConfigurationElement In Site.GetCollection("bindings")
If Binding("protocol").ToString.StartsWith("http", StringComparison.OrdinalIgnoreCase) Then
' IP is first of 3 colon-delimited parts, so just split on colon
' Example: 11.22.33.44:80:www.example.com (IP:Port:Host)
With Split(Binding("bindingInformation").ToString, ":")
IPAddress = .GetValue(0).ToString
HostName = .GetValue(2).ToString
' We found our site and got our bindings, so we can bail out
Exit Sub
End With
End If
Next
' We found our site but if we got this far, no HTTP(S) binding was found
' This should not happen in production...might happen in localhost testing
Exit Sub
End If
Next
' We never found our site...this should not happen in production...might happen in localhost testing
End Sub