2

I am trying to retrieve the remote Ip Address of the registrant on my registration page.

For testing, I am using a test app. In the controller;

private readonly IConfiguration _config;
    private IHttpContextAccessor _accessor;
    public HomeController(IConfiguration config, IHttpContextAccessor accessor)
    {
        _config = config;
        _accessor = accessor;
    }

and in the action result

 var ipAddress = _accessor.HttpContext.Connection.RemoteIpAddress;

that code is erring with the error message

  • Address 'ipAddress.Address' threw an exception of type 'System.Net.Sockets.SocketException' long {System.Net.Sockets.SocketException} Message "The attempted operation is not supported for the type of object referenced" string

I did NOT add a services call in Startup for the HttpContextAccessor because in reading about it, it is set up by default in Core 2.

UPDATE: I also tried using the X-Forwarded-For middleware as suggested by this blogpost X-Forwarded-For

but it still resolves to ::1 as the Ip address. Most likely because that middleware isn't working, Fiddler doesn't show the X-Forwarded-For in the headers

Any help appreciated as to why this error is occurring.

dinotom
  • 4,498
  • 10
  • 59
  • 124

1 Answers1

0

You don't need to inject IHttpContextAccessor into controller. Instead just use Request.HttpContext property of controller that returns context for the executing request:

public HomeController 
{
    [HttpGet]
    public string ActionMethod()
    {
        var address = this.Request.HttpContext.Connection.RemoteIpAddress;
    }
}
Set
  • 40,147
  • 18
  • 114
  • 133
  • @Set...That still returns the same thing... {::1} System.Net.IPAddress...which clearly is not an Ip address. Does it have anything to do with the fact I'm testing with localhost? – dinotom Apr 05 '18 at 12:52
  • @dinotom yes, check https://stackoverflow.com/questions/6408957/request-userhostaddress-issue-with-return-result-1 – Set Apr 05 '18 at 13:22
  • @Set...I changed the host file already. That doesn't solve it either. It is a socket exception error, that's what bugs me – dinotom Apr 05 '18 at 14:17