ASP.NET Core Cookie Url Encoded

Cookies mit .NET ist ganz einfach. Der C# Code mit klassischen .NET Framework und dotnet core ist ident. So setzt man ein Cookie für eine Domain mit einer bestimmten Dauer.

   1:   CookieOptions option = new CookieOptions();
   2:   option.Expires = DateTime.Now.AddDays(90);
   3:   option.Domain = ".ppedv.de";
   4:   Response.Cookies.Append("mycookie", "value", option);

Soweit so gut. Nur leider hat sich irgendwer bei Microsoft entschieden, Cookies zu codieren. Aus einem @ wird ein %40, wie im folgenden Screenshot aus dem Wert ä@& codiert %C3%A4%40%26 wird.

image

Das wäre solange kein Problem, wie man nicht Cookies mit alten Anwendungen sharen möchte. Die Dokumentation schweigt sich aus. Ich bin durch reinen Zufall über das Problem gestolpert, die Konsequenz ist aber frappierend.

Die Lösung ist direkt in den HTTP Header per Append den Cookie String im Raw Format anzuhängen. Folgende Helper Methode kapselt die Logik

   1:    public static class CookieExtensions
   2:          {
   3:    
   4:          public static void AppendRawCookie(this IHeaderDictionary header, string key, string value)
   5:              {
   6:                  header.Append("Set-Cookie", key + "=" + value + "; path=/");
   7:              }
   8:   
   9:              public static void AppendRawCookie(this IHeaderDictionary header, string key, string value, CookieOptions options)
  10:              {
  11:                  if (options == null)
  12:                      throw new ArgumentNullException("options");
  13:                  bool flag1 = !string.IsNullOrEmpty(options.Domain);
  14:                  bool flag2 = !string.IsNullOrEmpty(options.Path);
  15:                  bool hasValue = options.Expires.HasValue;
  16:                  header.Append("Set-Cookie",
  17:                      key + "=" + (value ?? string.Empty) + (!flag1 ? (string)null : "; domain=") +
  18:                      (!flag1 ? (string)null : options.Domain) + (!flag2 ? (string)null : "; path=") +
  19:                      (!flag2 ? (string)null : options.Path) + (!hasValue ? (string)null : "; expires=") +
  20:                      (!hasValue
  21:                          ? (string)null
  22:                          : options.Expires.Value.ToString("ddd, dd-MMM-yyyy HH:mm:ss ",
  23:                              (IFormatProvider)CultureInfo.InvariantCulture) + "GMT") +
  24:                      (!options.Secure ? (string)null : "; secure") + (!options.HttpOnly ? (string)null : "; HttpOnly"));
  25:              }
  26:          }

Nun kann ein Cookie wie gewohnt auch mit einer Email Adresse als Wert versehen werden in asp.net core Web Projekten.

   1:   Response.Headers.AppendRawCookie("mycookie","emai@l.de", option);
Kommentare sind geschlossen