locked
Unable to set cookies with web browser controls in windows phone app 7 & 8.

    Question

  • I am currently working on a win7 & 8 hybrid app.

    I need to maintain session in the hybrid apps.For that user has to login in app.Then inorder to maintain session,we will request a login authenetication service.Once we get the cookies in the web service response,we will inject those cookies to the windows phone web browser controls for displaying the relevent pages.

    To Log Cookies from Login service:

    Created a httpwebrequest for Log-in authentication by passing post parameters. Captured the set-cookies from callback-httpwebresponse which is a JSON response and saved it in a local Variable/Cookie Container/Cookie collections.

    To Set Cookies to other request :

    -> Passed cookies in the header field of web browser controls for all other requests. It dint work out.

    -> Created a HttpWebRequest and set the cookies in header field.

    Tried to assign with Headers[Cookies"] = variable data/cookie container data/cookie collection data.
    Assigned to request by creating a cookie container (request.CookieContainer = cookie container data/cookie collection
    data).
    -> Saved html web response in to a string variable from a asynchronous callback method and tried to load it in the web browser control.

    There is only one way for the web browser control to load html web page (ie,"webbrowser.NavigateToString(string html)" ).

    Triggered another event handler from the callback response method. we can see the html codes in the string variable. But It is displaying a black page in browser.

    Tried to save the html file in the isolated storage and made the browser to navigate to the file location. It is displaying a blank page.

    Tried to append "<

    <html><head></head> httpwebresponse <body></body></html>

    and stored it in a string variable. browser.NavigateToString(variable) - It is displaying a page without any CSS or
    images.Futher navigations in the page is also not happening.

    Impact : Session is not maintained throught the app.

    Tools used :

    Microsoft Visual studio ultimate 2010 Version 10, Microsoft .Net framework version 4.0, Windows Phone 7.1 SDK

    Can anyone help me with this.Thanks in Advance !!


    Wednesday, August 6, 2014 12:36 PM

Answers

  • Hi Sakthi,

    From your description, you are sending HttpWebRequest to remote server, the same time you are using WebBrowser to post request also. This will make thing more complex. My suggestion is to rethink your logic and try to make it easy. Try to use HttpWebRequest class to do GET and POST. When you get response form remote server, merge the html text into result string and then show in WebBrowser.

     > Is there any way for handling JSON response with web browser controls?

    Usually, Javescript handles JSON response in browser. But now we are using WebBrowser control in windows phone, it can call javascript method. But it’s hard to debug it. Choose a workaround is better than making it working.

    > How to maintain session with web browser controls?

    The extension methods in WebBrowser contains GetCookies method. It shows the truth that WebBrowser support Cookies. But you app cannot maintain session, so I have a thinking, are there some configuration mistake on remote server?

    > And is there any way to enable javascript with httpwebrequest?

    Per my understanding, the answer is no. I have not heard about this.

    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, August 11, 2014 2:29 AM
    Moderator
  • Hi Sakthi,

    > Is it possible to inject cookies to web browser controls??Is there any methods like "SetCookies".so that we can explicitly add cookies with web browser controls ??

    Unfortunately, there is no such methods like “SetCookies”. There is only GetCookies method, I think you need to work around this problem rather than finding a SetCookies method.

    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Wednesday, August 13, 2014 2:10 AM
    Moderator

All replies

  • Hi Sakthi,

    WebBrowser control in windows phone is used to display richly formatted HTML content from a remote web server or locally generated code. You can see that MSDN document introduces only display feature. Refer to see more information from http://msdn.microsoft.com/en-us/library/windows/apps/ff431797(v=vs.105).aspx. So I think you can use WebBroswer control to display content, but it’s not recommend to use the control to keep session alive.

    To work around this problem, you can use HttpWebRequest to get content form remote web server. This object can transfer cookie on request process and response process. See how to from http://msdn.microsoft.com/en-us/library/windows/apps/dd920298(v=vs.105).aspx. When you get content from http response, then you can display it in WebBrowser control. http://msdn.microsoft.com/en-us/library/windows/apps/ff431811(v=vs.105).aspx.

    Hope useful.

    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, August 7, 2014 3:17 AM
    Moderator
  • Hi Herro Wong,

    Thanks for your help !!

    Yes..I tried in that way also.But it is not working out.Session is not maintained.

    Is there any way for handling JSON response with web browser controls?

    For Lo-gin Authentication, we are hitting a service using httpwebrequest. It is providing a JSON response with set-cookies. I tried to load that JSON response in web browser by adding html tags and stored it in a string variable and navigated to it  using browser.NavigateToString method.

    It is loading the response. But for further requests, we are using browser.navigate method by providing post parameters.

    Idea behind this is.Once that JSON response is loaded in web browser,it will maintain the session using that set cookies until the browser ends.That is how it is working in PC browser.

    When i try the same thing in phone browser..Session is not maintained.

    How to maintain session with web browser controls?

    And is there any way to enable javascript with httpwebrequest?


    Thursday, August 7, 2014 6:02 AM
  • Hi Sakthi,

    From your description, you are sending HttpWebRequest to remote server, the same time you are using WebBrowser to post request also. This will make thing more complex. My suggestion is to rethink your logic and try to make it easy. Try to use HttpWebRequest class to do GET and POST. When you get response form remote server, merge the html text into result string and then show in WebBrowser.

     > Is there any way for handling JSON response with web browser controls?

    Usually, Javescript handles JSON response in browser. But now we are using WebBrowser control in windows phone, it can call javascript method. But it’s hard to debug it. Choose a workaround is better than making it working.

    > How to maintain session with web browser controls?

    The extension methods in WebBrowser contains GetCookies method. It shows the truth that WebBrowser support Cookies. But you app cannot maintain session, so I have a thinking, are there some configuration mistake on remote server?

    > And is there any way to enable javascript with httpwebrequest?

    Per my understanding, the answer is no. I have not heard about this.

    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, August 11, 2014 2:29 AM
    Moderator
  • Hi Herro wong,

    "I am just using the web browser controls to load the html contents".

    I am trying to load web browser with the html code from the httpwebresponse by storing it in a string variable.

    I created a httpwebrequest for a URL by setting cookies in it and getting a html page in a httpwebResponse.

    I am trying to display it in a web browser control by saving the code in a string variable. And navigating the browser("browse.NavigateToString(string)").

    But here page is not loaded properly.It is not displaying any css or images and displaying a message"You need to turn on java script in order to display the contents".

    I made the web browser property (IsScriptEnabled ) true before navigation. But it is still showing the message and contents are not loaded properly.

    Cookies are also not injected in to the web browser controls(session is not maintained through out the app).

    Is there any solution or work around for this ??

    Please refer to my code sample below :

    To log cookies  from login service :
     
    private void PostLoginRequest()
            {
                                           
                string AuthServiceUri = "Service URL";
                HttpWebRequest AuthReq = HttpWebRequest.Create(AuthServiceUri) as HttpWebRequest;
                AuthReq.CookieContainer = new CookieContainer();
                AuthReq.ContentType = "application/x-www-form-urlencoded";
                AuthReq.Method = "POST";
               
                AuthReq.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), AuthReq);
            }

            void GetRequestStreamCallback(IAsyncResult callbackResult)
            {
                HttpWebRequest Request = (HttpWebRequest)callbackResult.AsyncState;
           
                Stream postStream = Request.EndGetRequestStream(callbackResult);
                string postData = "Postdata parameters";
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();
                myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), Request);

            }

            void GetResponsetStreamCallback(IAsyncResult callbackResult)
            {

                try
                {
                   
                    HttpWebRequest callBackRequest = (HttpWebRequest)callbackResult.AsyncState;
                   
                    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
                   
                    CookieCollection cookiecollec = new CookieCollection();
                    cookiecollec = response.Cookies;
                    App.cookieCollection = cookiecollec; //global varaiable

                }
                catch (Exception e)
                {
    MessageBox.Show(e.Message);
                }
            }

    Another httpwebrequest with logged cookies :

     private void ResponsivePostURL(string PageName, string PostURL, string PostDatas)
                 {
                                                        
                            Uri ServiceUri = new Uri(PostURL); //Service URL

                            HttpWebRequest requestURL = HttpWebRequest.CreateServiceUri as HttpWebRequest;
                            requestURL.ContentType = "application/x-www-form-urlencoded";
                            requestURL.Method = "POST";                        
                            requestURL.CookieContainer = new CookieContainer();
                            requestURL.CookieContainer.Add(ServiceUri, App.cookieCollection);

                            requestURL.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), requestURL); 


                     }
     void GetResponsetStreamCallback(IAsyncResult callbackResult)
                 {

                     try
                     {

                         HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
                         HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
                        
                         
                        // MessageBox.Show(response.Cookies.ToString());

                         string responseString = "<html><head></head><body>";
                         Stream streamResponse = response.GetResponseStream();
                         StreamReader reader = new StreamReader(streamResponse);
                         responseString = responseString + reader.ReadToEnd() + "</body></html>";                   
                         streamResponse.Close();
                         reader.Close();
                         response.Close();
                         
                    

                         this.Dispatcher.BeginInvoke(() =>
                         {
                             
                             webBrowser.IsScriptEnabled = true;
                             webBrowser.NavigateToString(responseString);
                            
                         });
                     }
                     catch (Exception ex)
                     {
                         MessageBox.Show(ex.Message);
                     }
                 }


    Monday, August 11, 2014 7:07 AM

  •  > Is there any way for handling JSON response with web browser controls?

    Usually, Javescript handles JSON response in browser. But now we are using WebBrowser control 

    > How to maintain session with web browser controls?

    The extension methods in WebBrowser contains GetCookies method. It shows the truth that WebBrowser support Cookies. But you app cannot maintain session, so I have a thinking, are there some configuration mistake on remote server?


    Hi Herro Wong,

    Is it possible to inject cookies to web browser controls??Is there any methods like "SetCookies".so that we can explicitly add cookies with web browser controls ??

    Monday, August 11, 2014 12:43 PM
  • Hi Sakthi,

    > Is it possible to inject cookies to web browser controls??Is there any methods like "SetCookies".so that we can explicitly add cookies with web browser controls ??

    Unfortunately, there is no such methods like “SetCookies”. There is only GetCookies method, I think you need to work around this problem rather than finding a SetCookies method.

    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Wednesday, August 13, 2014 2:10 AM
    Moderator