2

我在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);

我控制器我在我的cookie中得到这样的值

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

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

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

我无法获得用户名。正如我所认为的那样,这些值采用 javscript 编码格式。如何获取用户名...谁能帮我找到解决方案...

4

2 回答 2

5

这应该可以解决问题!

 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);
       }
    }
于 2012-05-07T15:12:34.757 回答
1

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

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' )
    ;
}
于 2018-01-26T13:40:21.660 回答