在asp.net强类型的会话 [英] strongly typed sessions in asp.net
问题描述
原谅我,如果这个问题已经被问。 HttpContext.Current.Session [钥匙]
返回一个对象,我们将不得不将它转换为特定的键入
之前,我们可以使用它。我一直在寻找输入会议的各个实施
Pardon me if this question has already been asked. HttpContext.Current.Session["key"]
returns an object and we would have to cast it to that particular Type
before we could use it. I was looking at various implementations of typed sessions
<一个href=\"http://www.$c$cproject.com/KB/aspnet/typedsessionstate.aspx\">http://www.$c$cproject.com/KB/aspnet/typedsessionstate.aspx
<一href=\"http://weblogs.asp.net/cstewart/archive/2008/01/09/strongly-typed-session-in-asp-net.aspx\">http://weblogs.asp.net/cstewart/archive/2008/01/09/strongly-typed-session-in-asp-net.aspx
<一href=\"http://geekswithblogs.net/dlussier/archive/2007/12/24/117961.aspx\">http://geekswithblogs.net/dlussier/archive/2007/12/24/117961.aspx
而我觉得,我们需要一些更多的code(纠正我,如果我错了)添加到是SessionManager如果我们想添加一个新的键入
对象进入会话,无论是作为一种方法或作为一个单独的包装。我想我们可以使用泛型
and I felt that we needed to add some more code (correct me if I was wrong) to the SessionManager if we wanted to add a new Type
of object into session, either as a method or as a separate wrapper. I thought we could use generics
public static class SessionManager<T> where T:class
{
public void SetSession(string key,object objToStore)
{
HttpContext.Current.Session[key] = objToStore;
}
public T GetSession(string key)
{
return HttpContext.Current.Session[key] as T;
}
}
-
有什么内在的优势
使用Is there any inherent advantage in using
是SessionManager&LT;&类类别GT; .GetSession(sessionString)
不是用
HttpContext.Current.Session["sessionString"] as ClassType
- 我也在想这将是很好
有类似 -
我的想法是创建一个将存储在
键入
和对象,然后添加该对象会话(使用是SessionManager),用钥匙一SessionObject。检索时,投中的所有对象,以SessionObject
,获得类型(比如t)和对象(比如OBJ)和铸造OBJ
为T
并返回。 My thought was create a SessionObject which would store the
Type
and the object, then add this object to Session (using a SessionManager), with the key. When retrieving, cast all objects toSessionObject
,get the type (say t) and the Object (say obj) and castobj
ast
and return it.
是SessionManager [sessionString] = objToStoreInSession
,
但发现一个静态类不能有一个索引。是否有任何其他的方式来实现这一目标?SessionManager["sessionString"] = objToStoreInSession
, but found that a static class cannot have an indexer. Is there any other way to achieve this ?公共类SessionObject
{
公共类型类型{获取;设置;}
公共obj对象{获取;集;}结果
}这是行不通的,以及(作为返回签名将是相同的,但返回类型会有所不同)。
this would not work as well (as the return signature would be the same, but the return types will be different).
有储蓄的任何其他优雅的方式/检索更类型安全的方式在会话对象。
Is there any other elegant way of saving/retrieving objects in session in a more type safe way
推荐答案
有关处理会话的非常干净,维护,和光滑的方式,看看这个的帖子。你会惊奇地发现它是如何简单的就可以了。
For a very clean, maintainable, and slick way of dealing with Session, look at this post. You'll be surprised how simple it can be.
这篇关于在asp.net强类型的会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 我也在想这将是很好