Reputation: 1726
I'm trying to implement strongly-typed session variables in my asp.net MVC 5 project. I found this SO article which I'm basing mine off of but have some errors that I'm not familiar with due to my lack of knowledge of Extensions.
Here's the SessionExtensions
class:
public static class SessionExtensions
{
public static bool TryGetValue<T>(this HttpSessionStateBase session, out T value)
where T : class
{
var name = typeof(T).FullName;
value = session[name] as T;
var result = value != null;
return result;
}
public static void SetValue<T>(this HttpSessionStateBase session, T value)
{
var name = typeof(T).FullName;
session[name] = value;
}
public static void RemoveValue<T>(this HttpSessionStateBase session)
{
var name = typeof(T).FullName;
session[name] = null;
}
public static bool ValueExists(this HttpSessionStateBase session, Type objectType)
{
var name = objectType.FullName;
var result = session[name] != null;
return result;
}
public static bool TryGetAuthenticatedValue<T>(this HttpSessionStateBase session,
out T value)
where T : class
{
value = null;
if (HttpContext.Current.User != null
&& HttpContext.Current.User.Identity != null
&& HttpContext.Current.User.Identity.IsAuthenticated)
{
var name = typeof(T).FullName;
value = session[name] as T;
}
var result = value != null;
return result;
}
}
Which can easily assign whole objects to in code-behind:
DBRepository repo = new DBRepository();
var user = repo.GetAppUserInformation(userId);
Session.SetValue(user);
All this is working great. The issue/error I'm having is when I try to retrieve the User
object from the session. I see the TryGetAuthenticatedValue
extension method but when I try to use it in my .cshtml, I get an error.
<span class="username">
@{
if(Session.TryGetAuthenticatedValue(Project1.Models.User) != null)
{
//Display username from Session object.
}
}
</span>
The error is at design time on Project1.Models.User
and it states 'User' is a type, which is not valid in the given context.'
It may be worth noting that I'm using EF 6 and the User
class is auto-generated by EF.
Am I using the extension method wrong in the .cshtml file or is something else missing?
Upvotes: 0
Views: 365
Reputation: 1764
I think you need to change the code in your view to:
<span class="username">
@{
Project1.Models.User user = null;
if(Session.TryGetAuthenticatedValue(out user))
{
//Display username from Session object.
}
}
</span>
Since the method TryGetAuthenticatedValue returns a bool you don't need to check for null, and you need to pass in a variable of the type you want to retrieve not the type itself.
Hope that helps!
Upvotes: 2