在webRequest回调中了解发件人

时间:2012-05-23 08:11:39

标签: windows-phone-7

大家好,

我有很多使用相同导航事件处理程序的webView,我将它们导航到uri,执行httpwebrequest(添加cookie),然后在webview中设置内容并使用javascript添加css。

但是在某一点上我放弃了对发件人的引用,我不太明白如何解决这个问题,我不想做4个导航事件处理程序..

private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {

            wb1.Navigate(new Uri(site + notif, UriKind.Absolute));
            wb2.Navigate(new Uri(site + comptes, UriKind.Absolute));
            wb3.Navigate(new Uri(site + virements, UriKind.Absolute));
            wb4.Navigate(new Uri(site + autres, UriKind.Absolute));

            wb1.Navigating += new EventHandler<NavigatingEventArgs>(wb_Navigating);
            wb2.Navigating += new EventHandler<NavigatingEventArgs>(wb_Navigating);
            wb3.Navigating += new EventHandler<NavigatingEventArgs>(wb_Navigating);
            wb4.Navigating += new EventHandler<NavigatingEventArgs>(wb_Navigating);
        }

        void wb_Navigating(object sender, NavigatingEventArgs e)
        {
            Uri uri = e.Uri;
            e.Cancel = true;

            cookieContainer = new CookieContainer();
            //Add cookies here


            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
            req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)";
            req.Method = "POST";
            req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            req.CookieContainer = cookieContainer;
            req.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), req);
        }

        private void ReadWebRequestCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);

                using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
                {
                    string results = httpwebStreamReader.ReadToEnd();

                    Deployment.Current.Dispatcher.BeginInvoke(() => OnUiThreadResponse(results));

                }
                myResponse.Close();
        }

        private void OnUiThreadResponse(string results)
        {
            //HERE i need to know which WebBrowser fired the navigating event
            wbi.NavigateToString(results);
            //Add css with JS
            wbi.InvokeScript("");

        }

1 个答案:

答案 0 :(得分:1)

在发出请求时,您可以将sender传递给回调,或者您可以内联回调并通过闭包访问发件人。