1

我在从 HTTP 响应中获取 cookie 时遇到问题。我确定,该响应应该有 cookie,但我在我的应用程序中看不到它们。

这是我的代码:

    private static CookieContainer cookies = new CookieContainer();
    private static CookieContainer Cookies
    {
        get
        {
            return cookies;
        }
    }

    public static async Task<HttpStatusCode> SendPostRequest(string url, string postData)
    {
        if (url == null)
            throw new ArgumentNullException("url");

        if (postData == null)
            throw new ArgumentNullException("postData");

        HttpStatusCode statusCodeToReturn = HttpStatusCode.Forbidden;
        HttpWebRequest webRequest = HttpWebRequest.CreateHttp(url);
        webRequest.Method = "POST";
        var cookies = Cookies;
        webRequest.CookieContainer = cookies;
        //webRequest.SupportsCookieContainer = true;
        using (var requestStream = await webRequest.GetRequestStreamAsync())
        {
            var bytes = Encoding.UTF8.GetBytes(postData);
            requestStream.Write(bytes, 0, bytes.Length);
        }

        using (WebResponse response = await webRequest.GetResponseAsync())
        {
            statusCodeToReturn = WebResponseToHTTPStatusCode(response);
        }

        return statusCodeToReturn;
    }

Cookies(使用 Wireshark):

rack.session=BAh7BkkiD3Nlc3Npb25faWQGOgZFRiJFMzg1ZjYxNzIzNzQ4MmY5NmI3NTMw%0AYWMwZmRjNmVmZjMwMDk4OTgzZGUwNjRlNzIzODlmODNjYzE2YmVmMjNlOQ%3D%3D%0A--30d79cd2276c3236de11104852bba4b84bf80f26; path=/; HttpOnly
4

2 回答 2

1

问题在于返回的 Cookie。WP7 不支持没有设置 DOMAIN 的 Cookie。

于 2012-05-11T20:54:39.617 回答
0

我认为您可以只创建一个全局变量来保存 cookie。例如在您的 app.xaml.cs 文件中,您可以创建一个像这样的变量:

public CookieContainer GlobalCookie{get;set;}

并使 GloalCookie 等于您成功的 HttpWebRequest CookieContainer。

然后你可以在调用另一个API的时候使用这个变量。希望对你有帮助:)

于 2012-05-11T13:19:06.150 回答