我有一个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并不总是在网站范围内工作。
Cookie设置在两个地方之一... _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都会被清除,他们会获得标准的bootstrap主题。此时的网站网址将为 http://domain.com/sitename/
如果用户现在更改主题,则保存myTheme cookie,css链接将被更改,用户访问的任何其他页面将处于正确选择的主题中。
我的问题是,当用户返回主页时,该主页是相同的索引页,但由于操作链接,网址现在是 http://domain.com/sitename/Home/Index/ - 如果用户更改了主题现在,索引页面主题已更改,但导航到任何其他页面会给出上一个主题。返回主页将给出最新选择的主题...就好像现在有两个网站一个网站,一个专门用于主页/索引
不确定为什么会这样?
为了完整性,这是我的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 "";
}
任何帮助表示赞赏
答案 0 :(得分:0)
我的不好......我在每页的顶部和底部都有主页链接,并认为我所有的链接都在家里使用
@Html.ActionLink(" ", "Index", "Home")
检查所用页面底部的链接......
href="~/Home/Index"
使用热门链接始终将网址保留为http://domain.com/sitename/,而底部链接则为http://domain.com/sitename/Home/Index
将所有内容全部更改为操作链接或href="~/"
修复了问题...虽然我仍然不知道为什么会将Cookie路径设置为/(root)