Search code examples
asp.netvb.netasp.net-web-apiself-hosting

Get IP address of remote client in VB.NET self hosted API - Not using OWIN


I have a VB.NET project that uses the ASP.NET Web API, self-hosted.

I've been attempting to follow along with This link (Get the IP address of the remote host) to understand how to get the IP address of a client sending a message to my application, but every time I attempt to translate an item from the page referenced above to VB.NET, I run into errors.

I'd love to use the one-liner they referenced, below:

var host = ((dynamic)request.Properties["MS_HttpContext"]).Request.UserHostAddress;

However, that translates (using Telerik's .NET converter) to the following, which produces an error that 'Dynamic' is not a type:

Dim host = DirectCast(request.Properties("MS_HttpContext"), dynamic).Request.UserHostAddress

When using any of the other solutions in the article above, I end up stopping after getting the error that httpcontextwrapper is not defined, even after adding any references i can think of / that are mentioned on the page.

A requirement for a project I'm working on is that a request only be processed if it is from a specific IP address, and that this be handled by the application. So I'm attempting to get the IP address from this incoming request, so that it may be compared with a variable.


Solution

  • You can get the IP of client this way:

    Dim IP = ""
    If (Request.Properties.ContainsKey("MS_HttpContext")) Then
        IP = DirectCast(Request.Properties("MS_HttpContext"), HttpContextWrapper) _
                .Request.UserHostAddress
    ElseIf (Request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name)) Then
        Dim p = DirectCast(Request.Properties(RemoteEndpointMessageProperty.Name),  _
            RemoteEndpointMessageProperty)
        IP = p.Address
    End If
    

    You should add reference to System.Web and System.ServiceModel, also Imports Imports System.ServiceModel.Channels.

    Note

    To use dynamic way, you should first add Option Strict Off as first line of the code file, then:

    Dim ip = Request.Properties("MS_HttpContext").Request.UserHostAddress()