【发布时间】:2017-06-01 15:42:31
【问题描述】:
我正在尝试在我的 asp.net MVC 5 项目中实现强类型会话变量。我找到了 this SO article,这是我的基础,但由于我对扩展缺乏了解,所以有一些我不熟悉的错误。
这是SessionExtensions 类:
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;
}
}
这可以很容易地在代码隐藏中分配整个对象:
DBRepository repo = new DBRepository();
var user = repo.GetAppUserInformation(userId);
Session.SetValue(user);
这一切都很好。我遇到的问题/错误是当我尝试从会话中检索 User 对象时。我看到了 TryGetAuthenticatedValue 扩展方法,但是当我尝试在我的 .cshtml 中使用它时,我得到了一个错误。
<span class="username">
@{
if(Session.TryGetAuthenticatedValue(Project1.Models.User) != null)
{
//Display username from Session object.
}
}
</span>
错误是在设计时Project1.Models.User 并指出'User' is a type, which is not valid in the given context.'
值得注意的是,我使用的是 EF 6,User 类是由 EF 自动生成的。
是我在 .cshtml 文件中使用了错误的扩展方法还是缺少其他东西?
【问题讨论】:
-
Project1.Models.User是一个类。你的方法是否期望它传递一个类型? -
TryGetAuthenticatedValue使用out变量。您需要执行以下操作:Project1.Models.User usr; if(Session.TryGetAuthenticatedValue(out usr) && usr != null) ... -
您需要将 Project1.Models.User 类的对象作为输出参数传递给 Session.TryGetAuthenticatedValue 方法。您传递的是类,而不是对象。
标签: c# asp.net asp.net-mvc extension-methods