如何从 javascript asp.net mvc3 中设置的 cookie 中获取键值

How to get key Value from cookies which was set in javascript, asp.net mvc3

本文关键字:设置 获取 键值 cookie mvc3 javascript asp net      更新时间:2023-09-26

我在javascript中设置了一个cookie,像这样的东西

   function setCookie(c_name,value,exdays)
    {
       var exdate=new Date();
       exdate.setDate(exdate.getDate() + exdays);
       var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
       document.cookie = c_name + "=" + c_value;
    }
var  loginval = slmgusername=swetha.p + slmguserpassword = 12345678;
 setCookie("slmgusercredentails", loginval, 100);

控制我在我的饼干中获取这样的值

 HttpContext.Request.Cookies["slmgusercredentials"].Values = {slmgusername%253Dswetha.p%2526slmguserpassword%253D12345678}

当我试图从中获取用户名时,例如

 UserName = HttpContext.Request.Cookies["slmgusercredentials"].Values["slmgusername"].

我无法获取用户名。正如我认为的那样,这些值采用 javscript 编码格式。如何获取用户名...任何人都可以帮助我找到解决方案...

这应该可以解决问题!

 function ReadCookie()
    {
       var allcookies = document.cookie;
       alert("All Cookies : " + allcookies );
       // Get all the cookies pairs in an array
       cookiearray  = allcookies.split(';');
       // Now take key value pair out of this array
       for(var i=0; i<cookiearray.length; i++){
          name = cookiearray[i].split('=')[0];
          value = cookiearray[i].split('=')[1];
          alert("Key is : " + name + " and Value is : " + value);
       }
    }

从接受的答案中解决过期的问题。

function readKeyValuesFromCookie(){
    return document.cookie
        .split( ';' )
        .map( pair => pair.split( '=' ) )
        .filter( pair => pair.length == 2 )
        .map( pair => [ pair[0].trim(), pair[1].trim() ] )
        .filter( pair => pair[0] != 'expires' )
    ;
}