I have my web project in .NET Core 2.x. In the Login Controller, after the login, I save a token in the Session to have this token across pages.
My problem started when I wanted to test all controllers. If I call a controller from a test, HttpContext.Session is null.
Then I found this Mock for Session
public class MockHttpSession : ISession
{
Dictionary<string, object> sessionStorage = new Dictionary<string, object>();
public object this[string name]
{
get { return sessionStorage[name]; }
set { sessionStorage[name] = value; }
}
string ISession.Id
{
get {
throw new NotImplementedException();
}
}
bool ISession.IsAvailable
{
get {
throw new NotImplementedException();
}
}
IEnumerable<string> ISession.Keys
{
get { return sessionStorage.Keys; }
}
void ISession.Clear()
{
sessionStorage.Clear();
}
Task ISession.CommitAsync(CancellationToken cancellationToken
= default(CancellationToken))
{
throw new NotImplementedException();
}
Task ISession.LoadAsync(CancellationToken cancellationToken
= default(CancellationToken))
{
throw new NotImplementedException();
}
void ISession.Remove(string key)
{
sessionStorage.Remove(key);
}
void ISession.Set(string key, byte[] value)
{
sessionStorage[key] = value;
}
bool ISession.TryGetValue(string key, out byte[] value)
{
if (sessionStorage[key] != null)
{
value = Encoding.ASCII.GetBytes(sessionStorage[key].ToString());
return true;
}
else
{
value = null;
return false;
}
}
}
Now, I can access to the session but for every key I have to read its value like
var sessionName = new Byte[20];
bool nameOK = HttpContext.Session.TryGetValue("name", out sessionName);
if (nameOK)
string result = System.Text.Encoding.UTF8.GetString(sessionName);
Is there another simple way to save some values for a session across controllers and testable?
Update
As you see, with my mock values are in the session but GetString returns System.Byte[] instead of the value.

