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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14138872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:31:00  来源:igfitidea点击:

How to use sessions in an ASP.NET MVC 4 application?

asp.net-mvcsessionasp.net-mvc-4session-variables

提问by Thuto Paul Gaotingwe

I am new to ASP.NET MVC. I have used PHP before and it was easy to create a session and select user records based on the current session variables.

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

I have looked everywhere on the Internet for a simple step-by-step tutorial that can show me how to create and use sessions in my C# ASP.NET MVC 4 application. I want to create a session with user variables that I can access from anywhere in my controllers and be able to use the variables in my LINQ queries.

我在 Internet 上到处寻找一个简单的分步教程,该教程可以向我展示如何在我的 C# ASP.NET MVC 4 应用程序中创建和使用会话。我想使用用户变量创建一个会话,我可以从控制器中的任何位置访问该会话,并且能够在我的 LINQ 查询中使用这些变量。

回答by Jobert Enamno

Try

尝试

//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<Product>;

//to clear the session value

Session["products"]=null;

回答by Joseph Woodward

Due to the stateless nature of the web, sessions are also an extremely useful way of persisting objects across requests by serialising them and storing them in a session.

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

A perfect use case of this could be if you need to access regular information across your application, to save additional database calls on each request, this data can be stored in an object and unserialised on each request, like so:

一个完美的用例可能是,如果您需要访问整个应用程序中的常规信息,以在每个请求上保存额外的数据库调用,则可以将此数据存储在一个对象中并在每个请求上反序列化,如下所示:

Our reusable, serializable object:

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

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

    public string EmailAddress { get; set; }

    public string FullName { get; set; }
}

Use case:

用例:

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 */
    }

}

Once this object has been serialised, we can use it across all controllers without needing to create it or query the database for the data contained within it again.

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

Inject your session object using Dependency Injection

使用依赖注入注入会话对象

In a ideal world you would 'program to an interface, not implementation' and inject your serializable session object into your controller using your Inversion of Control container of choice, like so (this example uses StructureMap as it's the one I'm most familiar with).

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

public class WebsiteRegistry : Registry
{
    public WebsiteRegistry()
    {
        this.For<IUserProfileSessionData>().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;
    }
}

You would then register this in your Global.asax.csfile.

然后,您将在您的Global.asax.cs文件中注册它。

For those that aren't familiar with injecting session objects, you can find a more in-depth blog post about the subject here.

对于那些不熟悉注入会话对象的人,您可以在此处找到有关该主题的更深入的博客文章。

A word of warning:

一句警告:

It's worth noting that sessions should be kept to a minimum, large sessions can start to cause performance issues.

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

It's also recommended to not store any sensitive data in them (passwords, etc).

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

回答by Leniel Maccaferri

This is how session state works in ASP.NET and ASP.NET MVC:

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

ASP.NET Session State Overview

ASP.NET 会话状态概述

Basically, you do this to store a value in the Session object:

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

Session["FirstName"] = FirstNameTextBox.Text;

To retrieve the value:

要检索值:

var firstName = Session["FirstName"];

回答by Ulyses

You can store any kind of data in a session using:

您可以使用以下方法在会话中存储任何类型的数据:

Session["VariableName"]=value;

This variable will last 20 mins or so.

此变量将持续 20 分钟左右。

回答by Mukul Sharma

U can store any value in session like Session["FirstName"] = FirstNameTextBox.Text; but i will suggest u to take as static field in model assign value to it and u can access that field value any where in application. U don't need session. session should be avoided.

你可以在会话中存储任何值,如 Session["FirstName"] = FirstNameTextBox.Text; 但我会建议您将模型中的静态字段作为静态字段为其赋值,并且您可以在应用程序中的任何位置访问该字段值。你不需要会话。应该避免会话。

public class Employee
{
   public int UserId { get; set; }
   public string EmailAddress { get; set; }
   public static string FullName { get; set; }
}

on controller - Employee.FullName = "ABC"; Now u can access this full Name anywhere in application.

在控制器上 - Employee.FullName = "ABC"; 现在你可以在应用程序的任何地方访问这个全名。