.NET Core 中间件中的反向代理“set-cookie”响应未在浏览器中设置且未显示在 HttpResponseMessage 中

Reverse proxy in .NET Core Middleware “set-cookie” response does not set in browser and not showing in HttpResponseMessage

这里我正在制作一个反向代理服务器来绕过 ASP.NET 网络应用程序(在 this tutorial 之后)。我正在尝试从 HttpResponseMessage 读取会话 ID cookie。我也使用了一个饼干容器,但找不到它。在 ASP.NET 核心调用方法中实现,会话正常工作但无法在请求或响应中捕获会话 ID。

            public async Task Invoke(HttpContext context, IBrowserDetector detector)
            {
                //context.Session.SetString(SessionKeyName, "The Doctor");
                var browser = detector.Browser;
                var targetUri = BuildTargetUri(context.Request);
                if (context.Request.Method != HttpMethod.Get.Method)
                {
                    var remoteIp = context.Connection.RemoteIpAddress;
                    //var gg= context.Request.Headers.ContainsKey.;
                    var clienttdatetime = context.Request.Headers["Date"].ToString();
                    //_logger.LogDebug("Request from Remote IP address: {RemoteIp}", remoteIp);
                    var badIp = true;
                    var bytes = remoteIp.GetAddressBytes();
                    //var testIp = IPAddress.Parse(address);
                    //if (testIp.GetAddressBytes().SequenceEqual(bytes))
                    //{
                    //    badIp = false;
                    //    break;
                    //}
                    if (remoteIp.IsIPv4MappedToIPv6)
                    {
                        remoteIp = remoteIp.MapToIPv4();
                    }
                    IPAddress remoteIpAddress = context.Request.HttpContext.Connection.RemoteIpAddress;
                    string result = "";
                    if (remoteIpAddress != null)
                    {
                        // If we got an IPV6 address, then we need to ask the network for the IPV4 address 
                        // This usually only happens when the browser is on the same machine as the server.
                        if (remoteIpAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                        {
                            remoteIpAddress = System.Net.Dns.GetHostEntry(remoteIpAddress).AddressList
                    .First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
                        }
                        result = remoteIpAddress.ToString();
                    }
                    if (badIp)
                    {
                        //_logger.LogWarning(
                        //    "Forbidden Request from Remote IP address: {RemoteIp}", remoteIp);
                        //context.Response.StatusCode = StatusCodes.Status403Forbidden;
                        //return;
                    }
                }
    
    
                if (targetUri != null)
                {
                    CookieContainer cookies = new CookieContainer();
                    HttpClientHandler handler = new HttpClientHandler();
                    handler.CookieContainer = cookies;
                    var targetRequestMessage = CreateTargetMessage(context, targetUri);
    
                    using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
                    {
                        IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
                        foreach (Cookie cookie_ in responseCookies)
                           Console.WriteLine(cookie_.Name + ": " + cookie_.Value);
                        // ExtractCookiesFromResponse(responseMessage);
                        context.Response.StatusCode = (int)responseMessage.StatusCode;
                        CopyFromTargetResponseHeaders(context, responseMessage);
                        await responseMessage.Content.CopyToAsync(context.Response.Body);
                        //if(responseMessage.RequestMessage.RequestUri.ToString()== "http://localhost:51125/Menu.aspx")
                        //{
                        //Uri uri = new Uri("http://localhost:5000/login.aspx");
                        //Build the request
                       //Uri site = targetUri;
                       // HttpWebRequest request = (HttpWebRequest)WebRequest.Create(site);
                       // CookieContainer cookiesq = new CookieContainer();
                       // request.CookieContainer = cookiesq;
    
                       // //Print out the number of cookies before the response (of course it will be blank)
                       // Console.WriteLine(cookiesq.GetCookieHeader(site),"1");
    
                       // //Get the response and print out the cookies again
                       // using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                       // {
                       //     Console.WriteLine(cookiesq.GetCookieHeader(site), "2");
                       // }
    
                       // Console.ReadKey();
    
    
                        //}
                        var cookie = context.Request.Cookies["ASP.NET_SessionId"];
                    }
                    return;
                }
                await _nextMiddleware(context);
            }

------------------------------------------------------------------------------------
      public static IDictionary<string, string> ExtractCookiesFromResponse(HttpResponseMessage response)
        {
            IDictionary<string, string> result = new Dictionary<string, string>();
            IEnumerable<string> values;
            if (response.Headers.TryGetValues("Set-Cookie", out values))
            {
                SetCookieHeaderValue.ParseList(values.ToList()).ToList().ForEach(cookie =>
                {
                    result.Add(cookie.Name.ToString(), cookie.Value.ToString());
                });
            }
            return result;
        }

据我所知,您创建了 HttpClientHandler 但没有使用它来构建 HttpClient 来提出您的请求。您仍在使用对您创建的 cookie 容器一无所知的静态 _httpClient。 这应该是 CookieContainer 仍然为空的原因。

看看 here 了解如何从 HttpResponseMessage 获取 cookie。

               CookieContainer cookies = new CookieContainer();
               HttpClientHandler handler = new HttpClientHandler();
               handler.CookieContainer = cookies;
               _httpClient = new HttpClient(handler);
                var targetRequestMessage = CreateTargetMessage(context, targetUri);

                using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
                {
                    //var responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
                    IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
                    foreach (Cookie cookie in responseCookies)
                    {
                        if(cookie.Name=="ASP.NET_SessionId")
                        {
                            Console.WriteLine(cookie.Name + ": " + cookie.Value);
                            context.Response.Headers.Add("Set-Cookie", cookie.Name+"="+cookie.Value);
                        }
                        
                    }