Show All Cookies Snippet

This is a static method to display all cookies associated with the current domain. Wherever you use it, be sure to include System.Text and System.Web. This is essentially a C# translation of code found in Mike Pope's MSDN article "Basics of Cookies in ASP.NET," updated to use a StringBuilder and provide the output as an HTML table.

/// <summary>
/// Display all cookies associated with the current domain.
/// </summary>
/// <returns>Returns a string containing an HTML table which displays the 
/// Request.HttpCookieCollection including subkeys and values.</returns>
public static String CookiesToString()
{
Int16 ij;
StringBuilder output = new StringBuilder();
HttpCookie aCookie;
String subKeyName;
String subKeyValue;

output.Append("<table><tr><th>Cookie</th><th>Subkey</th><th>Value</th></tr>");
for (i=0;i < System.Web.HttpContext.Current.Request.Cookies.Count;i++)
  {
  output.Append("<tr>");
  aCookie = System.Web.HttpContext.Current.Request.Cookies[i];
  output.Append("<td>");
  output.Append(aCookie.Name);
  output.Append("</td>");
  if (aCookie.HasKeys)
    {
    System.Collections.Specialized.NameValueCollection cookieValues = aCookie.Values;
    String[] cookieValueNames = cookieValues.AllKeys;
    for (j=0;j<cookieValues.Count;j++)
      {
      subKeyName = HttpContext.Current.Server.HtmlEncode(cookieValueNames[j]);
      subKeyValue = HttpContext.Current.Server.HtmlEncode(cookieValues[j]);
      output.Append("<td>");
      output.Append(subKeyName);
      output.Append("</td><td>");
      output.Append(subKeyValue);
      output.Append("</td>");
      }
    }
    else
    {
      output.Append("<td></td><td>");
      output.Append(aCookie.Value);
      output.Append("</td>");
    }
    output.Append("</tr>");
  }
  return output.ToString();
}


Generated using PrettyCode.Encoder

No Comments