Wednesday, August 14, 2019

You probably should NOT try to scrape an IP address from a web site from Visual Studio project that is not the UI.

My various Sabina Spielrein flavored blog posts about finding yourself suggest as much but I was really wrong. I'm sorry.

If you try to dig up an IP address by a call tucked away to the infrastructure project of your application's onion architecture like it is an external dependency you are just going to get the IP address of the server running the app as best as I can gleam. I recommend getting the IP from the browser hitting a controller endpoint at the controller itself like so in .NET Core:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
namespace FluffyNothing.UserInterface.Controllers
{
   public class HomeController : Controller
   {
      private IHttpContextAccessor _accessor;
      
      public HomeController(IHttpContextAccessor accessor)
      {
         _accessor = accessor;
         _timekeeping = timekeeping;
      }
      
      public IActionResult Index()
      {
         var x = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();

 
 

There is not a Controller versus ApiController divide anymore as of MVC 6 and thus this trick will work with ReST calls too. There are however two other things you may see which may trouble you:

  1. ::1 which is what you are going to have for an IP when you run locally and this stumbling point is exactly the sort of thing that took my down the wrong rabbit hole wherein I was scrapping IP addresses from websites at the outside. When you spin up a server at Rackspace and actually run stuff there it will behave differently than when you run Kestrel out of Visual Studio 2019. I promise.
     
  2. Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'MyApp.UserInterface.Controllers.HomeController'. ...which means that in the IoC stuff in Startup.cs you will need:
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Now I feel better about me:

No comments:

Post a Comment