0

在这里,我正在制作一个反向代理服务器来绕过 ASP.NET Web 应用程序(遵循本教程)。我正在尝试从中读取会话 ID cookie HttpResponseMessage。我也使用了一个 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;
        }
4

2 回答 2

0
               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);
                        }
                        
                    }
于 2020-10-01T11:55:14.003 回答
0

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

在这里查看以了解如何从HttpResponseMessage.

于 2020-09-30T16:26:51.593 回答