Search code examples
c#cookies.net-6.0dotnet-httpclient

Handling a comma inside a cookie value using C# and .NET 6


I encountered an issue while trying to read the content of a third-party cookie.

The cookie contains values like: 110, IN, ABC, X, Y,,,,,

I'm reading the cookie using:

_httpContextAccessor.HttpContext.Request.Cookies["key"];

But it did not return all the data.

Note: this is third-party cookie and I can not encode it to get rid of it.


Solution

  • I got a fix: instead of getting cookie value like

    Get as below:

     private string ParseCookie(string cookieKey)
     {
        var cookieHeader = 
        _httpContextAccessor.HttpContext.Request.Headers["Cookie"].ToString();
        if (!string.IsNullOrEmpty(cookieHeader))
        {
           // Split the cookies by ';' which is the delimiter for multiple cookies
           var cookies = cookieHeader.Split(';');
           foreach (var cookie in cookies)
           {
            // Split the individual cookie by '='
            var parts = cookie.Split('=');
            if (parts.Length == 2)
            {
                var key = parts[0].Trim();
                var value = parts[1].Trim();
    
                if (key == cookieKey)
                {
                    // Process the comma-separated value
                    return Uri.UnescapeDataString(value);
                    // Perform any necessary actions based on the cookie value
                    break;
                }
            }
        }
      }
      return String.Empty;
    }