停止url编码cookie

考虑以下ASP.net web api控制器方法。 出于演示目的,它返回一个cookie。 session-id cookie具有base64编码数据。 当我使用response.Headers.AddCookies(new CookieHeaderValue[] { cookie });将cookie添加到响应中时response.Headers.AddCookies(new CookieHeaderValue[] { cookie }); 它url对数据进行编码(文档在这里 )。 我有没有办法在没有编码的情况下附加cookie?

  public HttpResponseMessage LogMeIn() { var response = Request.CreateResponse(new Models.UserAuthResponse()); var cookie = new CookieHeaderValue("session-id", "K2QRkQaSnwCBpRrAgI1K3w9kTgbArc+xdIJI64e2hz0="); cookie.Expires = DateTimeOffset.Now.AddDays(1); cookie.Domain = ".example.com"; cookie.Path = "/"; response.Headers.AddCookies(new CookieHeaderValue[] { cookie }); return response; } 

我有同样的问题,因为我想创建Lotus Domino SSO Web应用程序使用的LTPA令牌cookie,这个cookie是base64编码的,并使用cookie中的特殊字符,如“+ = ….”。 我找到了解决这个问题的三种方法:

  1. Startup.cs中的OWIN扩展

app.Use((context, next) => { context.Response.Headers....; //here decode and replace the cookies return next.Invoke(); });

  1. 使用cookie加载页面后使用javascript:

    document.cookie = encodeURIComponent(document.cookie);

  2. 或者最好的方法是创建这样的扩展:

     ///  /// ///  public static class CookieExtensions { ///  /// Add a new cookie and value /// ///  ///  ///  public static void AppendUrlDecodedCookie(this IHeaderDictionary header, string key, string value) { header.AppendValues("Set-Cookie", key + "=" + value + "; path=/"); } ///  /// Add a new cookie /// ///  ///  ///  public static void AppendUrlDecodedCookie(this IHeaderDictionary header, string key, string value, CookieOptions options) { if (options == null) throw new ArgumentNullException("options"); bool flag1 = !string.IsNullOrEmpty(options.Domain); bool flag2 = !string.IsNullOrEmpty(options.Path); bool hasValue = options.Expires.HasValue; header.AppendValues("Set-Cookie", key + "=" + (value ?? string.Empty) + (!flag1 ? (string) null : "; domain=") + (!flag1 ? (string) null : options.Domain) + (!flag2 ? (string) null : "; path=") + (!flag2 ? (string) null : options.Path) + (!hasValue ? (string) null : "; expires=") + (!hasValue ? (string) null : options.Expires.Value.ToString("ddd, dd-MMM-yyyy HH:mm:ss ", (IFormatProvider) CultureInfo.InvariantCulture) + "GMT") + (!options.Secure ? (string) null : "; secure") + (!options.HttpOnly ? (string) null : "; HttpOnly")); } } 

你可以像这样使用它:

 response.Headers.AppendUrlDecodedCookie("key", "val"); 

要么

 response.Headers.AppendUrlDecodedCookie("key", "val", new Microsoft.Owin.CookieOptions { Path = "/", Domain = ="domain.com", Expires = Date... }); 

这解决了这个问题。