ASP.NET MVC 中的会话变量 [英] Session variables in ASP.NET MVC

查看:28
本文介绍了ASP.NET MVC 中的会话变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Web 应用程序,该应用程序将允许用户浏览网站内的多个网页,并提出某些请求.用户输入的所有信息都将存储在我创建的对象中.问题是我需要从网站的任何部分访问这个对象,我真的不知道实现这一点的最佳方法.我知道一种解决方案是使用会话变量,但我不知道如何在 asp .net MVC 中使用它们.我应该在哪里声明会话变量?还有其他办法吗?

I am writing a web application that will allow a user to browse to multiple web pages within the website making certain requests. All information that the user inputs will be stored in an object that I created. The problem is that I need this object to be accessed from any part of the website and I don't really know the best way to accomplish this. I know that one solution is to use session variables but I don't know how to use them in asp .net MVC. And where would I declare a session variable? Is there any other way?

推荐答案

我想你会想要考虑事情是否真的属于会话状态.这是我发现自己不时做的事情,这是对整个事情的一种很好的强类型方法,但是在将事情放入会话上下文时应该小心.并非所有东西都应该存在,因为它属于某个用户.

I would think you'll want to think about if things really belong in a session state. This is something I find myself doing every now and then and it's a nice strongly typed approach to the whole thing but you should be careful when putting things in the session context. Not everything should be there just because it belongs to some user.

在 global.asax 中钩住 OnSessionStart 事件

in global.asax hook the OnSessionStart event

void OnSessionStart(...)
{
    HttpContext.Current.Session.Add("__MySessionObject", new MySessionObject());
}

您可以从代码中 HttpContext.Current 属性 != null 的任何位置检索该对象.我使用扩展方法来做到这一点.

From anywhere in code where the HttpContext.Current property != null you can retrive that object. I do this with an extension method.

public static MySessionObject GetMySessionObject(this HttpContext current)
{
    return current != null ? (MySessionObject)current.Session["__MySessionObject"] : null;
}

这样你就可以在代码中

void OnLoad(...)
{
    var sessionObj = HttpContext.Current.GetMySessionObject();
    // do something with 'sessionObj'
}

这篇关于ASP.NET MVC 中的会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆