从编码cookie中停止IResponseCookies.Append()。 dotnetcore 2.0

时间:2018-01-18 14:50:12

标签: c# asp.net asp.net-mvc .net-core owin

我们正在构建一个dotnetcore 2.0网络应用程序,它通过http从旧系统接收cookie并在响应中设置cookie。

当我调试应用程序时,我可以看到cookie.value不是url编码的,但在调用append之后,set-cookie标头是url编码的。这是有问题的,因为传统的cookie需要取消编码,因为旧版应用程序会按原样读取它们。

    public static void AddCookie(this IResponseCookies cookies, Cookie cookie)
    {
        cookies.Append(cookie.Name, cookie.Value, new CookieOptions
        {
            Domain = cookie.Domain,               
            Expires = cookie.Expires == DateTime.MinValue ? null : (DateTimeOffset?) cookie.Expires,
            HttpOnly = cookie.HttpOnly,
            Path = cookie.Path,
            Secure = cookie.Secure
        });
    }

有没有办法防止它们被编码?一个旗帜或设置在哪里?

我尝试编写一个owin中间件,但set-cookie标头始终为空。

public class CookieDecode
{
    private readonly RequestDelegate _next;

    public CookieDecode(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        var x = context.Response.Headers;
        var y = x["set-cookie"];
        //y is always empty
        await _next.Invoke(context);
    }
}

想法?

1 个答案:

答案 0 :(得分:1)

不,没有选项可以避免URL编码。但是,here is what Append正在做。您可以尝试以与他们相同的方式手动设置标题吗?

    public void Append(string key, string value, CookieOptions options)
    {
        if (options == null)
        {
            throw new ArgumentNullException(nameof(options));
        }

        var setCookieHeaderValue = new SetCookieHeaderValue(
            Uri.EscapeDataString(key),
            Uri.EscapeDataString(value))
        {
            Domain = options.Domain,
            Path = options.Path,
            Expires = options.Expires,
            MaxAge = options.MaxAge,
            Secure = options.Secure,
            SameSite = (Net.Http.Headers.SameSiteMode)options.SameSite,
            HttpOnly = options.HttpOnly
        };

        var cookieValue = setCookieHeaderValue.ToString();

        Headers[HeaderNames.SetCookie] = StringValues.Concat(Headers[HeaderNames.SetCookie], cookieValue);
    }