如何在ASP.NET MVC 4应用程序中使用会话?

我是ASP.NET MVC的新手。我以前用过PHP,创建一个会话并根据当前会话变量选择用户记录是很容易的。

我在互联网上到处寻找一个简单的分步教程,告诉我如何在我的C# ASP.NET MVC 4应用程序中创建和使用会话。我想创建一个带有用户变量的会话,我可以从我的控制器中的任何地方访问这些变量,并且能够在我的LINQ查询中使用这些变量。

-预先感谢!

解决办法

尝试

//adding data to session
//assuming the method below will return list of Products

var products=Db.GetProducts();

//Store the products to a session

Session["products"]=products;

//To get what you have stored to a session

var products=Session["products"] as List;

//to clear the session value

Session["products"]=null;
评论(9)

由于网络的无状态特性,会话也是一种非常有用的方式,通过序列化对象并将其存储在会话中,可以跨请求持久化对象。

一个完美的用例是,如果你需要在你的应用程序中访问常规信息,以节省每次请求的额外数据库调用,这些数据可以存储在一个对象中,并在每次请求中不被序列化,像这样。

我们的可重用的、可序列化的对象:

[Serializable]
public class UserProfileSessionData
{
    public int UserId { get; set; }

    public string EmailAddress { get; set; }

    public string FullName { get; set; }
}

使用情况:

public class LoginController : Controller {

    [HttpPost]
    public ActionResult Login(LoginModel model)
    {
        if (ModelState.IsValid)
        {
            var profileData = new UserProfileSessionData {
                UserId = model.UserId,
                EmailAddress = model.EmailAddress,
                FullName = model.FullName
            }

            this.Session["UserProfile"] = profileData;
        }
    }

    public ActionResult LoggedInStatusMessage()
    {
        var profileData = this.Session["UserProfile"] as UserProfileSessionData;

        /* From here you could output profileData.FullName to a view and
        save yourself unnecessary database calls */
    }

}

一旦这个对象被序列化,我们就可以在所有的控制器中使用它,而不需要再去创建它或查询数据库中的数据了。

使用依赖注入法注入你的会话对象

在一个理想的世界里,你会'根据接口编程,而不是实现'并使用你选择的反转控制容器将可序列化的会话对象注入控制器,就像这样(这个例子使用StructureMap,因为它是我最熟悉的)。

public class WebsiteRegistry : Registry
{
    public WebsiteRegistry()
    {
        this.For().HybridHttpOrThreadLocalScoped().Use(() => GetUserProfileFromSession());   
    }

    public static IUserProfileSessionData GetUserProfileFromSession()
    {
        var session = HttpContext.Current.Session;
        if (session["UserProfile"] != null)
        {
            return session["UserProfile"] as IUserProfileSessionData;
        }

        /* Create new empty session object */
        session["UserProfile"] = new UserProfileSessionData();

        return session["UserProfile"] as IUserProfileSessionData;
    }
}

然后你将在你的Global.asax.cs文件中注册这个对象。

对于那些不熟悉注入会话对象的人来说,你可以找到一篇关于这个主题的更深入的博文这里

警告:

值得注意的是,会话应保持在最低限度,大型会话可能开始导致性能问题。

我们也建议不要在其中存储任何敏感数据(密码等)。

评论(3)

这就是会话状态在ASP.NET和ASP.NET MVC中的工作方式。

ASP.NET会话状态概述

基本上,你这样做是为了在Session对象中存储一个值。

Session["FirstName"] = FirstNameTextBox.Text;

要检索该值。

var firstName = Session["FirstName"];
评论(3)