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)
-
0
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
IHttpContextAccessorinterface.You can also get the IPaddress by injecting the
IClientInfoProviderinterface.Markdown is supportedCopy & paste or drag & drop images (max 30 MB per image) -
0
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(); } }`Markdown is supportedCopy & paste or drag & drop images (max 30 MB per image) -
0
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
Markdown is supportedCopy & paste or drag & drop images (max 30 MB per image) -
0
Thank you
Markdown is supportedCopy & paste or drag & drop images (max 30 MB per image)