软件开发
开发分享
软件下载

C#处理Cookie中逗号值问题

时间:2010-01-14 来源:juhe99 点击量:

Cookie中逗号值问题及解决方案

问题描述:Cookie 的"Value"="xxxxx,xxxxx"部分无效

在一些网站中有时候会遇到Cookie的值包含逗号,但是在.NET中Cookie的值是不能直接使用逗号的。

问题重现

如果使用形如以下代码:

Cookie cookie = new Cookie("name", "xxxxx,xxxxx");

会报错:

Cookie 的"Value"="xxxxx,xxxxx"部分无效

解决方案

在使用的时候可以将逗号替换为%2C(URL编码)写入Cookie中:

方法一:分步设置

Cookie cookie = new Cookie();
cookie.Name = "name";
cookie.Value = "xxxxx%2Cxxxx";

方法二:直接构造

Cookie cookie = new Cookie("name", "xxxx%2Cxxxx");

技术说明:

  • 原因:逗号(,)是Cookie规范中的保留字符,不能直接在值中使用

  • 解决方案:使用URL编码将逗号编码为%2C

  • 读取时:需要相应地进行URL解码以恢复原始值