Cookie adding another entry instead of replacing e

2019-07-26 05:33发布

I am using the popular jquery cookie plugin to set a session cookie value via javascript like so:

function ChangeLoginUser(sel) {
    var selectedUser = sel.options[sel.selectedIndex].value;
    $.cookie("LoginUser", selectedUser);
    location.reload(true); //refresh
}

This function is called after user selects from a site global drop-down box option.

  • Change the value on page1 - the cookie is set CookieName = Value1.
  • Go to page2 - The cookie is persisting correctly
  • Change the drop-down value to value2 - Fiddler now shows two cookies by the same name with both values like this:
CookieName = value2
CookieName = value1

I don't understand why this is happening. I need to keep only one cookie of this name. The new value is supposed to replace the old one.

1条回答
霸刀☆藐视天下
2楼-- · 2019-07-26 06:05

Ok. It looks like the problem was with the cookie path. Each URL can have a separate cookie with the same name. The solution is to set the path to be domain wide like this:

$.cookie("LoginUser", selectedUser, { path: '/' });

or, if you need to narrow it down to only your application you can do it like this:

$.cookie("LoginUser", selectedUser, { path: AppPath });

where AppPath can be set in the beginning of your shared layout

<script type="text/javascript">
    var AppPath = '@Url.Content("~/")'
</script>
查看更多
登录 后发表回答