你如何在VB.NET的HTTPCookie中使用Ampersand?

时间:2009-12-02 14:19:29

标签: vb.net cookies ampersand

我将Cookie保存到用户,如下所示......

Dim searchCookie As HttpCookie = New HttpCookie("SearchCriteria")
searchCookie.Item("SearchText") = FullSearchCriteria.SearchText
searchCookie.Item("SearchType") = FullSearchCriteria.SearchType

SearchText存储他们在上一页中输入的值。我们观察到cookie中是否有&符号(例如Tyne& Wear),然后cookie不会保存后续值(SearchType)。

如果输出cookie会发生什么:

SearchText=Tyne &

很明显,&符号令人困惑。有没有办法防止这种情况发生?

3 个答案:

答案 0 :(得分:5)

您可以使用URLEncode方法。

类似的东西:

imports HttpContext.Current
...
Dim searchCookie As HttpCookie = New HttpCookie("SearchCriteria")
searchCookie.Item("SearchText") = Server.UrlEncode(FullSearchCriteria.SearchText)
searchCookie.Item("SearchType") = Server.UrlEncode(FullSearchCriteria.SearchType)

这对only certain characters are allowed in cookies至关重要,其中包含ampersands breaking them等字符。

答案 1 :(得分:1)

D'哦!我真是个笨蛋......

Dim searchCookie As HttpCookie = New HttpCookie("SearchCriteria")
searchCookie.Item("SearchText") = HttpContext.Current.Server.UrlEncode(FullSearchCriteria.SearchText)
searchCookie.Item("SearchType") = HttpContext.Current.Server.UrlEncode(FullSearchCriteria.SearchType)

答案 2 :(得分:1)

需要对cookie值进行编码。我不是VB专家,但看起来这是用方法

完成的
System.Web.HttpUtility.UrlEncode