【问题标题】:cookies are not site widecookie 不是站点范围的
【发布时间】:2016-05-04 23:51:40
【问题描述】:

我有一个 MVC 网站,我正在使用 cookie 来存储网站主题。我有以下功能来设置 cookie...它位于 _Layout.vbhtml 中,它是我所有网站的“母版页”。

function setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        document.cookie = cname + "=" + cvalue + "; " + expires; + "path=/";
    }

即使我指定了根路径,我的 cookie 也并不总是适用于整个站点。

cookies 设置在两个位置之一...在 _Layout.vbhtml 我也有...

$(document).ready(function () {
        //Set User Theme Preferences
        //First check theme cookie and if null Or empty set to default values
        var $theme = getCookie('myTheme');

        if ($theme == "") {
            //theme cookie does Not exists Or has expired
            setCookie('myTheme', 'bootstrap', 90);
            $theme = "bootstrap";
        }

        if ($theme != "bootstrap") {
            //theme is not bootstrap so change css link
            $("#cssTheme").attr("href", ('@Url.Content("~/Content/bootstrap.min.css")').replace("bootstrap", $theme));
        }
    })

而且我在 Home/Index.vbhtml 中也有这个点击功能 - 只有用户可以更改主题的地方。

$("button[data-theme]").click(function () {
            $theme = $(this).data("theme")
            setCookie('myTheme', $theme, 90);
            $("head link#cssTheme").attr("href", ('@Url.Content("~/Content/bootstrap.min.css")').replace("bootstrap", $theme));
        });

因此,如果用户启动网站,所有 cookie 都会被清除,他们将获得标准引导主题。此时的网站网址将是 http://domain.com/sitename/

如果用户现在更改主题,myTheme cookie 已保存,css 链接将更改,用户访问的任何其他页面都将位于正确选择的主题中。

我的问题是当用户返回主页时,该主页是相同的索引页面,但由于操作链接,现在 URL 是 http://domain.com/sitename/Home/Index/ - 如果用户 现在更改主题,索引页面主题已更改,但导航到任何其他页面会提供以前的主题。返回主页将给出最新选择的主题...就好像现在有两个 cookie 一个站点范围和一个专门用于主页/索引

不知道为什么会这样?

为了完整起见,这是我的 getCookie 函数,它位于 _Layout.vbhtml 中

function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1);
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }

任何帮助表示赞赏

【问题讨论】:

    标签: javascript jquery cookies


    【解决方案1】:

    我的错...我在每个页面的顶部和底部都有主页链接,并认为我所有的主页链接都已使用

    @Html.ActionLink(" ", "Index", "Home")
    

    在检查所用页面底部的链接时...

     href="~/Home/Index"
    

    使用顶部链接始终将 URL 保留为 http://domain.com/sitename/,而底部链接始终保留为 http://domain.com/sitename/Home/Index

    将它们全部更改为 Action Links 或 href="~/" 解决了问题...虽然我仍然不知道为什么会这样,因为 cookie 路径设置为 / (root)

    【讨论】:

      猜你喜欢
      • 2012-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-26
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      相关资源
      最近更新 更多