You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将HttpWebResponse的Cookies复制到HttpWebRequest的CookieContainer中

Copying Response Cookies to HttpWebRequest's CookieContainer

Got it, let's break down how to transfer those cookies from your response to the new request's CookieContainer properly. Here's what you need to do:

Step 1: Capture the Response Cookies and URI

First, make sure you're storing both the cookies from the response and the actual URI that sent them (this is critical for ensuring cookies are applied to the correct domain/path):

CookieCollection responseCookies = null;
Uri responseUri = null;

using (HttpWebResponse httpWebResponse = (HttpWebResponse)templateRequest.GetResponse())
{
    // Grab the cookies returned in the response
    responseCookies = httpWebResponse.Cookies;
    // Get the exact URI that served this response (handles redirects automatically)
    responseUri = httpWebResponse.ResponseUri;

    using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
    {
        // Optional: Read response content if you need to process it
        string responseContent = streamReader.ReadToEnd();
    }
}

Step 2: Initialize CookieContainer and Add Cookies

Next, create a CookieContainer instance, add all captured cookies to it (using the response URI to enforce proper cookie scope), then assign it to your new request:

// Create your target request
HttpWebRequest newTemplateRequest = base.GetTemplateRequest("https://apps.runescape.com/runemetrics/profile/profile?activities=20");

// Initialize the CookieContainer (it's null by default on HttpWebRequest)
CookieContainer cookieContainer = new CookieContainer();

// Add each cookie to the container if we have valid data
if (responseCookies != null && responseUri != null)
{
    foreach (Cookie cookie in responseCookies)
    {
        cookieContainer.Add(responseUri, cookie);
    }
}

// Attach the container to your request
newTemplateRequest.CookieContainer = cookieContainer;

Key Details to Keep in Mind:

  • Why responseUri? Cookies are tied to specific domains and paths. Using the response's actual URI ensures the CookieContainer knows exactly when to send these cookies in future requests (avoids issues with subdomains or redirected endpoints).
  • Null Safety: Always check if responseCookies or responseUri are null to prevent runtime errors (in case the response returned no cookies).
  • Reusable Container: If you're making multiple requests to the same domain, you can reuse the same CookieContainer—it will automatically manage cookies for subsequent calls (including updating expired cookies or new ones returned in responses).

内容的提问来源于stack exchange,提问作者refactorcoding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:06:04