停止 IResponseCookies.Append() 编码 cookie.网络核心 2.0 [英] Stop IResponseCookies.Append() from encoding cookies. dotnetcore 2.0

查看:54
本文介绍了停止 IResponseCookies.Append() 编码 cookie.网络核心 2.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We are building a dotnetcore 2.0 web app that receiving cookies from a legacy system via http and setting the cookies in the response.

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

When I debug the app I can see that cookie.value is not url encoded but after calling append the set-cookie headers are url encoded. This is problematic as the legacy cookies need to be unencoded as legacy apps read them as they are.

    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
        });
    }

有没有办法防止它们被编码?标志或某处的设置?

Is there a way to prevent them being encoded? A flag or setting somewhere?

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

I tried writing an owin middleware but the set-cookie header is always empty.

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);
    }
}

想法?

推荐答案

不,没有避免 URL 编码的选项.但是,herecode>Append 正在做.您可以尝试像他们一样手动设置标题吗?

No, there is no option to avoid the URL encoding. However, here is what Append is doing. Can you try manually setting the header the same way they do?

    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);
    }

这篇关于停止 IResponseCookies.Append() 编码 cookie.网络核心 2.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆