Safari 和 Asp.net 中 cookie 的奇怪问题 [英] Strange problem with cookies in Safari and Asp.net

查看:20
本文介绍了Safari 和 Asp.net 中 cookie 的奇怪问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Asp.net 的登录页面上有一个奇怪的问题,这个问题只发生在 Safari 上.

I have a strange problem on my login page in Asp.net this problem only happens with Safari.

验证用户后,我从数据库中获取用户名(数据库中的字段为 UTF8)并将其保存在 cookie 中.问题是,当用户的名称带有特殊字符时,我会在未登录的情况下被重定向到我来自的页面.例如,Moller"工作正常,用户登录但不是Møller".

When the user is validated I fetch the name of the user from the database (the field in the database is UTF8) and save it in a cookie. The problem is that when the user has a name with special characters I get redirected to the page where I came from without being logged in. For example "Moller" works fine and the user is logged in but not "Møller".

同样,这种情况只发生在 Safari 中,并且名称中有特殊字符时.不起作用的行是:Response.Cookies["userInfo"]["name"] = getNameFromUserid(userid);

Again this is only happening with Safari and when I have special characters in the name. The row that isn't working is: Response.Cookies["userInfo"]["name"] = getNameFromUserid(userid);

这是我的代码:

string userid = validUserWithEmail(TextBoxEmail.Text, TextBoxPassword.Text);
if (userid != null) {
    //VALID USER
    Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(30);
    Response.Cookies["userInfo"]["name"] = getNameFromUserid(userid);

    FormsAuthentication.RedirectFromLoginPage(userid, CheckBoxPersistCookie.Checked);
} 
else
{
    //NOT A VALID USER SHOW A MESSAGE FOR THE USER OR SOMETHING
}

推荐答案

Safari 不会将 cookie 的值设置为非 ASCII 字符,其他浏览器在显示非 ASCII 字符方面可能无法预测.由于任何浏览器的 cookie 值中也不允许使用分号,因此我建议使用 UrlEncode/UrlDecode.

Safari will not set cookies with non-ASCII characters in their value and other browsers can be unpredictable in how they display non-ASCII characters. As semi-colon is also not allowed in cookie values for any browser I would recommend using UrlEncode/UrlDecode.

如果您只是编写 cookie 并且无法控制站点读取/显示要放入 URLDecode 的值,您也可以执行以下操作:

If you are just writing the cookie and do not have control over the site reading/displaying the value to put in the URLDecode you can also do something like this:

ckCookie.Value = (Server.HtmlEncode( strSpecialCharacters )).Replace(";","");

这将确保在 cookie 中设置完整的字符串,即使没有 ; Safari、Chrome、Firefox 和 IE 仍能识别 html 代码并且读取时不需要解码.

This will ensure the full string is set in the cookie and Safari, Chrome, Firefox and IE will still recognize the html codes even without the ; and does not require decoding when read.

有关 cookie 规范的详细答案,请参阅:cookie 中允许的字符

For a longer answer on cookie specs see: Allowed characters in cookies

这篇关于Safari 和 Asp.net 中 cookie 的奇怪问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆