'Sharing value from custom middleware to anywhere
I'm trying to pass the client IP address from the middleware to anywhere in the project.
I have made three attempts (session, cookie, items), but none of them is working.
I get the value using custom middleware as follows:
public Task Invoke(HttpContext httpContext)
{
var httpConnectionFeature = httpContext.Features.Get<IHttpConnectionFeature>();
var remoteIpAddress = httpConnectionFeature?.RemoteIpAddress;
//var remoteIpAddress = httpContext.Connection.RemoteIpAddress;
if (remoteIpAddress.ToString() != "::1")
{
var cookieOptions = new CookieOptions
{
Secure = true,
HttpOnly = true,
SameSite = SameSiteMode.None,
Expires = DateTime.Now.AddMinutes(5),
IsEssential = true
};
httpContext.Response.Cookies.Append("anonymousIP", remoteIpAddress.ToString(), cookieOptions);
httpContext.Session.SetString("anonymousIP", remoteIpAddress.ToString());
httpContext.Items.Add("anonymousIP", remoteIpAddress.ToString());
}
return _next(httpContext);
}
but I can't receive it!
var ctxt = Context.GetHttpContext();
var x = ctxt.Session.GetString("anonymousIP");
var y = ctxt.Items["anonymousIP"];
var z = ctxt.Request.Cookies["anonymousIP"];
is there anything wrong? is it possible to share a value from the middleware to anywhere?
Solution 1:[1]
for a similar requirement, I created a class as below
public class CurrentUserService : ICurrentUserService
{
private readonly IHttpContextAccessor _httpContextAccessor;
public CurrentUserService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public string MyVariable
{
get
{
// get data as you need, e.g. from header or request object.
return _httpContextAccessor.HttpContext.Request.Headers["MyVariable"].ToString();
}
}
}
then using Dependency Injection - inject "ICurrentUserService" anywhere you need.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Walnut |
