asp.net-mvc – 在BaseController中获取/设置HttpContext会话方
发布时间:2020-12-16 04:03:48 所属栏目:asp.Net 来源:网络整理
导读:我在BaseController类中创建了Get / Set HttpContext会话方法,还创建了Mocked HttpContextBase并创建了Get / Set方法. 哪个是使用它的最佳方式. HomeController : BaseController { var value1 = GetDataFromSession("key1") SetDataInSession("key2",(objec
我在BaseController类中创建了Get / Set HttpContext会话方法,还创建了Mocked HttpContextBase并创建了Get / Set方法.
哪个是使用它的最佳方式. HomeController : BaseController { var value1 = GetDataFromSession("key1") SetDataInSession("key2",(object)"key2Value"); Or var value2 = SessionWrapper.GetFromSession("key3"); GetFromSession.SetDataInSession("key4",(object)"key4Value"); } public class BaseController : Controller { public T GetDataFromSession<T>(string key) { return (T) HttpContext.Session[key]; } public void SetDataInSession(string key,object value) { HttpContext.Session[key] = value; } } 要么 public class BaseController : Controller { public ISessionWrapper SessionWrapper { get; set; } public BaseController() { SessionWrapper = new HttpContextSessionWrapper(); } } public interface ISessionWrapper { T GetFromSession<T>(string key); void SetInSession(string key,object value); } public class HttpContextSessionWrapper : ISessionWrapper { public T GetFromSession<T>(string key) { return (T) HttpContext.Current.Session[key]; } public void SetInSession(string key,object value) { HttpContext.Current.Session[key] = value; } } 解决方法
第二个似乎是最好的.虽然我可能会将这两个作为扩展方法写入
HttpSessionStateBase,而不是将它们放入基本控制器中.像这样:
public static class SessionExtensions { public static T GetDataFromSession<T>(this HttpSessionStateBase session,string key) { return (T)session[key]; } public static void SetDataInSession<T>(this HttpSessionStateBase session,string key,object value) { session[key] = value; } } 然后在控制器,帮助器或具有HttpSessionStateBase实例的内容中使用它: public ActionResult Index() { Session.SetDataInSession("key1","value1"); string value = Session.GetDataFromSession<string>("key1"); ... } 编写会话包装器在ASP.NET MVC中是无用的,因为框架提供的HttpSessionStateBase已经是一个抽象类,可以在单元测试中轻松模拟. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 向.NET电子邮件添加附件
- asp.net – 为什么DropDownList.SelectedValue依赖于viewst
- 身份验证 – ASP:使用JMail进行SMTP身份验证失败
- 本地iis上的asp.net核心Windows身份验证
- asp.net-mvc – 在带有Web Essentials的Visual Studio 2013
- asp-classic – asp CDO.Message.1错误’80040213’传输无法
- asp.net – dotnet运行OR dotnet手表与开发环境从命令行?
- asp.net-mvc-4 – 如何在视图页面上缩小脚本块内的JavaScri
- WPAD查询从ASP.NET调用webservice
- ASP.Net应用程序是否有内存限制?
推荐文章
站长推荐
- asp.net-mvc – 为“简单”SaaS启动选择ORM(ASP.
- attributes – 利用属性版本控制在Swagger中利用
- asp.net – Web部署项目:不预编译发布
- 给微软的日志框架写一个基于委托的日志提供者
- asp.net – 访问radGrid列中的值
- 使用Azure表存储进行ASP.NET会话
- asp.net-mvc-3 – ASP.NET MVC语言更改链接
- asp.net-mvc – F#支持最新的asp.net 5和MVC6
- asp.net-mvc – ASP.NET MVC – 向ActionLinks添
- asp.net-mvc-4 – Razor MVC,在哪里可以通过母版
热点阅读