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

查看:110
本文介绍了在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());
}

在code任何地方的HttpContext.Current属性!= NULL可以retrive该对象。我这样做有一个扩展的方法。

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;
}

这种方式,你可以在code

This way you can in code

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

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

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