ASP.net Session原理「建议收藏」

ASP.net Session原理「建议收藏」1.创建SessionMgr类usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;//////SessionMgr的摘要说明///publicclassSessionMgr{privatestaticIDiction

大家好,又见面了,我是你们的朋友全栈君。1.创建SessionMgr类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
///SessionMgr 的摘要说明
/// </summary>
public class SessionMgr
{

  
    private static IDictionary<string, IDictionary<string, object>> data = new Dictionary<string, IDictionary<string, object>>();
    public static IDictionary<string, object> GetSession(string sessionId)
    {
        if (data.ContainsKey(sessionId))
        {
            return data[sessionId];
        }
        else
        {
            IDictionary<string, object> session = new Dictionary<string, object>();
            data[sessionId] = session;
            return session;
        }
    }

    public static IDictionary<string, object> GetSession()
    {
        throw new NotImplementedException();
    }

}

2.页面读取服务端Session

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class sessionweb : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["MySessionId"] == null)
        {
           string sessionId = Guid.NewGuid().ToString();
            Response.SetCookie(new HttpCookie ("MySessionId",sessionId ));
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string sessionId = Request.Cookies["MySessionId"].Value;
        IDictionary <string ,object > session= SessionMgr.GetSession(sessionId );
        session["服务端"] = "333";
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        string sessionId = Request.Cookies["MySessionId"].Value;
        IDictionary<string, object> session = SessionMgr.GetSession(sessionId );
       Button2 .Text  = Convert.ToString(session ["服务端"]);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/159547.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号