WebAPI Encoding Cookie Values

I set cookies on my ASP.NET api controller. This is my piece of code:

var cookie = new CookieHeaderValue(cookieName, cookieValue) { Expires = cookieExpires, Domain =cookieDomain, Path= "/" }; response.Headers.AddCookies(new[] {cookie}); 

I noticed that the cookie value is automatically encoded. So abc== becomes abc%3d%3d . This does not happen on a regular MVC controller.

How to prevent its coding?

+4
source share
2 answers

It is encoded, because otherwise the string value "abc ==" will result in an invalid cookie. Encoding is automatic to prevent invalid characters such as "=" from appearing in the cookie.

I'm not sure that you mean that this does not happen in MVC, maybe when you access the cookie in the request, is it decoded?

See https://en.wikipedia.org/wiki/HTTP_cookie#Setting_a_cookie

EDIT If the string "abc ==" is a Base64 encoded byte array, you can get arround using System.Web.HttpServerUtility UrlTokenEncode / UrlTokenDecode instead. Then there will be no other encoding.

+2
source

To prevent the use of PLS โ€‹โ€‹below, wherever you read cookies:

 Server.UrlDecode("Your string"); 

It will remove this '% 3d' and convert it back to '='

+1
source

All Articles