【问题标题】:when does a session get created in any asp.net web application?什么时候在任何 asp.net Web 应用程序中创建会话?
【发布时间】:2014-05-09 03:06:54
【问题描述】:

是否为每个页面请求创建会话?即使我们没有启用任何表单身份验证或在应用程序中创建任何会话对象?

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    会话状态数据在所有数据表单之间共享,但用于单用户全局数据。

        Declaration For the session :
        Session["Key"] = "value";
    
        Session data are stored on the server side.
    
        Session state variables are declared when session times out.
        By default time out for session is 20 minutes.
    

    例如:

        **If you are using session & you are executing the first session web form & suppose you have navigated your page from web-form 1 to web-form 2.
        Then Session output will be the same.
    
        If suppose your o/p for web-form 1 is "2".
        Then if you have closed the browser & copy and paste the same URL to another browser.
        then you will notice that o/p will be the same Because In your URL session ID is present.
        there for it will have the same o/p.
        This is very Important to understand about session if you want to use the session in your application.**  
    
        ie session data session state data shared across all the web-form but only fr single user.
    
        For every session Unique session ID is generated.
        But is you have changed your session then new session ID is generated meaning it is only for single user.
    

    【讨论】:

    • 我了解到,当第一个请求到达服务器时,会为应用程序创建一个唯一 SessionID,并且它映射为用户及其各自会话对象(如果有)的唯一身份。如果对我的理解有任何更正,请告诉我。感谢所有回复。
    • 是的,你完全正确,Shekar。但要记住的一件事是,如果您想要从一个网页到另一个网页的一些数据,那么它非常有用。
    【解决方案2】:

    来自Microsoft Docs

    SessionID 属性用于唯一标识具有服务器上会话数据的浏览器。 SessionID 值由 ASP.NET 随机生成,并存储在浏览器中的非过期会话 cookie 中。 SessionID 值随后在 cookie 中随每个请求发送到 ASP.NET 应用程序。

    因此,当浏览器请求需要会话状态的资源时,如果会话状态模块找不到现有会话 ID(在 ASP.NET 会话 cookie 中,或者在无 cookie 会话的情况下的 URL 中),那么在会话 ID cookie 中创建并返回一个新的会话 ID。

    会话 ID 用于检索一组会话状态值(通常称为“会话变量”)。只要会话存在,存储在这种“变量”中的数据就会一直可用。如果会话超时,或者 AppDomain 重新启动,或者 cookie 变得不可用,则会话“变量”将包含 null。必须为此准备使用会话状态的代码:

    错误代码:

    string user = Session["User"];
    int length = user.Length;   // NullReferenceException if session was expired
    

    更好的代码:

    string user = Session["User"];
    if (user == null) {
        // Do without the user information
    } else {
        int length = user.Length; // User information is available
    }
    

    【讨论】:

    • -1:报价准确,但您的解释与报价不符。
    • 不,和连接无关
    • 但是如果页面甚至没有访问Session 对象怎么办。无论如何都会创建会话吗?这是关于发送到浏览器的cookie。如果应用程序不使用它,我认为它不必存在。
    • 我有一个疑问,可以说,我刚刚在 asp.net Mvc 应用程序中创建了一个 AboutUs 页面,它只返回一个 View ,这是否会为用户的请求创建一个新会话还是 Session 是使用我们应用程序中的代码创建的,例如表单身份验证?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    相关资源
    最近更新 更多