Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Linx 98 posts 259 karma points
    Oct 18, 2022 @ 08:18
    Linx
    0

    How to get CurrentContext and IP address?

    Hi guys

    I'm attempting to replicate some functionality from an old site and im wondering how do i get the CurrentContext in Umbraco 10 and the IP address?

    My original code is

    var userIP = HttpContext.Current.Request.GetUserIPAddress();
    

    I just cant find the equivalent code when using Umbraco 10?

    Thanks for any help

  • Markus Rytterkull 36 posts 207 karma points
    Oct 18, 2022 @ 09:10
    Markus Rytterkull
    0

    Hi!

    This has changed in .net core. Try using this instead:

    Context.Request.HttpContext.Connection.RemoteIpAddress
    
  • Linx 98 posts 259 karma points
    Oct 18, 2022 @ 09:36
    Linx
    0

    Hi @Markus_Rytterkull

    I dont have Context and if i do then i dont see Request, do you know what namespace i may need?

    Could you also provide me with the source for this so i can try and have a look.

    Thanks

  • Markus Rytterkull 36 posts 207 karma points
    Oct 18, 2022 @ 10:02
    Markus Rytterkull
    100

    Are you doing this in a Controller or a View?

    In my views, I have access to Context automatically, which is nice.

    In a controller, you have to do a few steps:

    1. Add a private field to hold your context: private readonly IHttpContextAccessor _httpContext;

    2. Add IHttpContextAccessor httpContextAccessor to your constructor ... , IHttpContextAccessor httpContextAccessor) : base(logger, compositeViewEngine, umbracoContextAccessor)

    3. set your private field: _httpContext = httpContextAccessor;

    4. Use it your controller :-) _httpContext.HttpContext.Request...

    So this a more a .net core thing than an umbraco thing.

    Here is a controller example:

    public class ContentFolderController : RenderController
    {
        private readonly IHttpContextAccessor _httpContext;
    
        public ContentFolderController(ILogger<ContentFolderController> logger,
            ICompositeViewEngine compositeViewEngine,
            IUmbracoContextAccessor umbracoContextAccessor,
            IHttpContextAccessor httpContextAccessor)
            : base(logger, compositeViewEngine, umbracoContextAccessor)
        {
            _httpContext = httpContextAccessor;
        }
    
        public override IActionResult Index()
        {
            //use context to get ip
            var userIp = _httpContext.HttpContext.Connection.RemoteIpAddress;
    
    
            return View("~/Views/SmartContentFolder.cshtml", CurrentPage);
        }
    }
    
  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies