How do you use an Ampersand in an HTTPCookie in VB.NET?

落爺英雄遲暮 提交于 2019-12-04 05:24:58

问题


I have a cookie saved to the user as follows...

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

The SearchText stores a value they have input in a previous page. We have observed if there is an ampersand in the cookie (eg Tyne & Wear), then the cookie doesn't save subsequent values (SearchType).

What happens is the cookie is output like this:

SearchText=Tyne &

Obviously the ampersand is confusing the cookie. Is there a way to prevent this happening?


回答1:


You can use the URLEncode method.

Something like:

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

This is essential as only certain characters are allowed in cookies with characters such as ampersands breaking them.




回答2:


D'oh! I'm such a dork...

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)



回答3:


The cookie values need to be encoded. I'm no VB expert, but it looks like this is done with the method

System.Web.HttpUtility.UrlEncode


来源:https://stackoverflow.com/questions/1833176/how-do-you-use-an-ampersand-in-an-httpcookie-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!