由于HttpWebRequest对象的状态错误,无法设置CookieContainer?

时间:2011-11-02 10:52:16

标签: c# windows-phone-7 cookies silverlight-4.0

我目前正在尝试使用Visual Studio中的windows phone 7 silverlight登录并获取远程服务器的cookie。我设法登录并获得了一个成功的登录结果,但是当我尝试输入代码来获取cookie时,它就失败了。

它产生错误“由于HttpWebRequest对象的状态,无法设置CookieContainer。”在我的代码“request.CookieContainer = new CookieContainer();”

任何人都可以帮助我吗?我似乎无法找到错误,我试着查看文档和示例,但没有运气。以下是我在Windows Phone 7上的完整代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.IO.IsolatedStorage;

namespace Testing_Login_
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void buttonLogin_Click(object sender, RoutedEventArgs e)
        {
            //HttpWebRequest req = WebRequest.Create();
            string POST_ADDRESS = "http://mywebsite.com";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(POST_ADDRESS, UriKind.Absolute));  
            request.Method = "POST";  
            // don't miss out this  
            request.ContentType = "application/x-www-form-urlencoded";  
            request.BeginGetRequestStream(new AsyncCallback(RequestReady), request);  


        }
        // Sumbit the Post Data  
        void RequestReady(IAsyncResult asyncResult)
        {
            HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
            Stream stream = request.EndGetRequestStream(asyncResult);

            // Hack for solving multi-threading problem  
            // I think this is a bug  
            this.Dispatcher.BeginInvoke(delegate()
            {
                // Send the post variables  
                StreamWriter writer = new StreamWriter(stream);
                writer.Write("username=" + textBoxUsername.Text + "&password=" + passwordBoxSTAMP.Password);
                writer.Flush();
                writer.Close();

                request.CookieContainer = new CookieContainer();

                request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
            });
        }

        // Get the Result  
        void ResponseReady(IAsyncResult asyncResult)
        {
            HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

            this.Dispatcher.BeginInvoke(delegate()
            {
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);
                // get the result text  
                string result = reader.ReadToEnd();


                if (result == "TRUE")
                {
                    MessageBox.Show("Login Successful!");

                    //CookieCollection cookieValue = response.Cookies;
                    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (IsolatedStorageFileStream isfs = isf.OpenFile("CookieExCookies",  FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            using (StreamWriter sw = new StreamWriter(isfs))
                            {
                                foreach (Cookie cookieValue in response.Cookies)
                                {
                                    sw.WriteLine("Cookie: " + cookieValue.ToString());
                                }
                                sw.Close();
                            }
                        }

                    }
                    //MessageBox.Show(cookieValue.ToString());

                }
                else if (result == "ICRED")
                {
                    MessageBox.Show("Username or Password incorrect!");
                }
                else
                {
                    MessageBox.Show("Unknown Error!"+result);
                }
            });
        }
        private void ReadFromIsolatedStorage()
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream isfs =
                   isf.OpenFile("CookieExCookies", FileMode.Open))
                {
                    using (StreamReader sr = new StreamReader(isfs))
                    {
                        textBoxCookies.Text = sr.ReadToEnd();
                        sr.Close();
                    }
                }

            }
        }

    }
}

1 个答案:

答案 0 :(得分:0)

移动线: -

request.CookieContainer = new CookieContainer();

RequestReady,并在构建完成后将其放入buttonLogin_Click

或者因为你没有在任何地方重新使用它。

或者如果事实上要真正工作的东西你需要重新使用它然后构造并将其保存在其他地方(例如类中的字段)并将其分配给之前创建的每个Request对象您调用任何BeginGetRequestStreamBeginGetResponse