只是想分享我如何在应用程序中使用会话。我真的很喜欢这个实现(关于在控制器和扩展方法中访问 ASP.NET MVC Session[] 数据的建议? https://stackoverflow.com/questions/2213052/suggestions-for-accessing-asp-net-mvc-session-data-in-controllers-and-extension/2213232#2213232)使用会话,因为它可以轻松地将会话换成另一个商店或用于测试目的。
查看实现,它让我想起了我在其他项目中使用的 ObjectStore,将对象序列化为二进制或 xml 并存储在数据库或文件系统中。
因此,我简化了我的接口(以前 T 必须是一个类)并提出了以下内容:
public interface IObjectStore {
void Delete(string key);
T Get<T>(string key);
void Store<T>(string key, T value);
IList<T> GetList<T>(string key);
}
我的会话存储实现:
public class SessionStore : IObjectStore
{
public void Delete(string key) {
HttpContext.Current.Session.Remove(key);
}
public T Get<T>(string key) {
return (T)HttpContext.Current.Session[key];
}
public void Store<T>(string key, T value) {
HttpContext.Current.Session[key] = value;
}
public IList<T> GetList<T>(string key) {
throw new NotImplementedException();
}
}
然后,我在基本控制器的构造函数中接收 IObjectStore,然后可以像这样使用它来向其他控制器公开属性:
public string CurrentCustomer {
get {
string currentCustomer =
sessionStore.Get<string>(SessionKeys.CustomerSessionKey);
if (currentCustomer == null) {
currentCustomer = Guid.NewGuid().ToString();
sessionStore.Store<string>(SessionKeys.CustomerSessionKey, currentCustomer);
}
return currentCustomer;
}
}
我对这种方法非常满意。