rng
rng

Reputation: 41

WebAPI encoding cookie values

I am setting cookies on my ASP.Net web api controller. This is my code portion:

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

I noticed the value of cookie is being automatically encoded. So abc== becomes abc%3d%3d. This doesn't happen on a regular MVC controller.

How do I prevent his encoding from happening?

Upvotes: 4

Views: 3212

Answers (2)

Harshad Vekariya
Harshad Vekariya

Reputation: 1052

To prevent it pls use below, wherever you read cookies:

Server.UrlDecode("Your string");

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

Upvotes: 1

Martin Vich
Martin Vich

Reputation: 1082

It's encoded because otherwise "abc==" string value would result to an invalid cookie. Encoding is automatic to prevent invalid characters like "=" to be present in the cookie.

I'm not sure what do you mean that it doesn't happend in MVC, maybe that when you access the cookie value in request then it's decoded?

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

EDIT If "abc==" string is Base64 encoded byte array then you can get arround by using System.Web.HttpServerUtility UrlTokenEncode/UrlTokenDecode methods instead. Then no other encoding will occur.

Upvotes: 2

Related Questions