mvc中seeeion和cook的用法

public ActionResult A()

{
     Session[ "test" ]= "123" ;
     return  View();
}
public  ActionResult B()
{
     string  v=Session[ "test" ].ToString();
     return  View();
}

这样创建session是获取不到的,原因是因为创建的session是Controller下的(这里自己可以深入研究一下),而不是System.Web.HttpContext.Current的session。

想要所有的地方都可以获取session的值,应该是如下写法

public ActionResult A()

{
     System.Web.HttpContext.Current.Session[ "test" ]= "123" ;
     return  View();
}
public  ActionResult B()
{
     string  v=System.Web.HttpContext.Current.Session[ "test" ].ToString();
     return  View();
}
//cook的用法
清除session

HttpCookie Cookie = null;

    Cookie = new HttpCookie("User");

    if (Cookie != null)

    {

      Cookie.Expires = DateTime.Now.AddDays(-1);

      Response.Cookies.Set(Cookie);

    }

 
-存

HttpCookie cookie = new HttpCookie("MyCook");
DateTime dt = DateTime.Now;
cookie.Expires = dt.AddMinutes(5);   //五分钟过期
cookie.Values.Add("userid", "dsc");
cookie.Values.Add("username", HttpUtility.UrlEncode("段世昌"));    //注意汉子存储的时候,如果直接存的是汉字,读取的时候值是乱码,因此要先把汉子编码,读取的时候再解码就ok了,字母就不用编码了
Response.AppendCookie(cookie);

-读

if (Request.Cookies["MyCook"] != null)
{
                    // HttpCookie cookie=Request.Cookies["MyCook"];

                 //string s=cookie["userid"].ToString();//整行
                string c= Request.Cookies["MyCook"]["userid"].ToString();//整行
               string c3= HttpUtility.UrlDecode(Request.Cookies["MyCook"]["username"]);     //汉字要解码的

}

转载于:https://www.cnblogs.com/DSC1991/p/8623753.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值