Base solution for your next web application
Open Closed

Is there any way to retrieve the requesting IP on the application layer? #7404


User avatar
1
yoshrepublic created

I allow a few types of unauthenticated requests to some methods in an appservice on the application layer. I would like capture the requesting IP address. Is there any way to do that? Do I have access to the context?


4 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team

    I suggest that you put the interception IP function on the web layer, you can do it through middleware or mvc filters. Because in the web layer you can access the HttpContext.

    In the aspnet core, the application service layer can also access the HttpContext. Need to inject the IHttpContextAccessor interface.

    You can also get the IPaddress by injecting the IClientInfoProvider interface.

  • User Avatar
    0
    yoshrepublic created

    Thank you. I have added the below class to the web.core layer and the interface to the core layer. It works like a charm. My only question is should I be using ISingletonDependency instead?

    ` class AppContextAccessor: IAppContextAccessor, ITransientDependency { private readonly IHttpContextAccessor _httpContextAccessor;

        public AppContextAccessor(IHttpContextAccessor contextAccessor)
        {
            _httpContextAccessor = contextAccessor;
        }
    
        public string GetIpAddress()
        {
            var httpContext = _httpContextAccessor.HttpContext;
            return httpContext.Connection.RemoteIpAddress.ToString();
        }
    
        public string GetBrowserInfo()
        {
            var httpContext = _httpContextAccessor.HttpContext;
            return httpContext.Request.Headers["User-Agent"].ToString();
        }
    }`
    
  • User Avatar
    0
    maliming created
    Support Team

    If you don't need it, you don't have to use ISingletonDependency Please refer to: https://medium.com/volosoft/asp-net-core-dependency-injection-best-practices-tips-tricks-c6e9c67f9d96

  • User Avatar
    0
    yoshrepublic created

    Thank you