If your service really needs access to the full
HttpContext
, then you can inject the
IHttpContextAccessor[
^] service and use that to access the current context. However, you cannot inject services into a
static
method; you would need to inject the service into the caller, and pass the context as a parameter.
It would be better to create specific service interface(s) for your class library's exact requirements, and inject/pass an implementation that delegates to the current context. That way, you make your code more testable. Eg:
Class library:
public interface ISessionParamProvider
{
string? GetSessionParam(string name);
}
private static string? GetSessionParam(ISessionParamProvider provider, SessionParams param)
{
string myName = "GetSessionParam";
NLogger.Instance.Trace($"{myName} Asking for value ({param})");
string? result = provider.GetSessionParam(param.GetDescription());
if (result is null)
{
return null;
}
if (!param.Equals(SessionParams.Config))
{
NLogger.Instance.Trace($"{myName} Returning with ({result})");
}
else
{
NLogger.Instance.Trace($"{myName} Returning with ({result.CutByPrefixSuffix(3, 3)})");
}
return result;
}
Web application:
public class SessionParamProvider : ISessionParamProvider
{
private readonly IHttpContextAccessor _contextAccessor;
public SessionParamProvider(IHttpContextAccessor contextAccessor)
{
ArgumentNullException.ThrowIfNull(contextAccessor);
_contextAccessor = contextAccessor;
}
public string? GetSessionParam(string name)
{
var session = _contextAccessor.HttpContext?.Session;
if (session is null)
{
return null;
}
byte[] value;
if (!session.TryGetValue(name, out value))
{
return null;
}
return Encoding.UTF8.GetString(value);
}
}
var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddHttpContextAccessor();
builder.Services.AddTransient<ISessionParamProvider, SessionParamProvider>();
...
Access HttpContext in ASP.NET Core | Microsoft Learn[
^]