Search code examples
c#postwebviewwindows-store-apps

Post data with a request in a Windows Store app WebView - using C#


I have the following scenario in my app:

At first startup, the user can register an account. The app then gets a pair (int user_id, string session_id) from my webserver and stores that data in-app.

In my app I use a WebView which lets the user look at some content of my site. Using the user_id and the session_id, he gets logged in automatically (after that, server side session and cookies are created).

I did not want to use an url scheme like http://mobile.mysite.com/?user_id=int&session_id=string, so I decided to use http post to send the user_id and session_id.

In iOS it was very easy:

// Post the user data and load the website in the webview
NSString *startUrl = @"http://mobile.mysite.com/";
NSString *post = [NSString stringWithFormat:@"user_id=%@&session_id=%@, [user uid], [user sessionId]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:startUrl]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[post dataUsingEncoding: NSUTF8StringEncoding]];
[webView loadRequest:request];

So here I am, having done the same structure in my Windows 8 Store app in C#. Unfortunately, WebView does not let me post the user info to the server.

Do you have an idea how I could solve my problem?

One idea would be to make a http request and share the cookie with the WebView. But that does not look very elegant to me...


Solution

  • POST with WebView in Windows 8.1

    Or even better, use WebView.NavigateWithHttpRequestMessage(HttpRequestMessage requestMessage).

    You can use a Windows.Web.Http.HttpRequestMessage to set the HTTP method and the request content among other things.

    E.g.:

    HttpRequestMessage request = new HttpRequestMessage(
        HttpMethod.Post,
        new Uri("http://localhost"));
    request.Content = new HttpStringContent(
        String.Format("user_id={0}&session_id={1}", "Chinese", "food"));
    webView.NavigateWithHttpRequestMessage(request);
    

    That would be equivalent to the following HTTP request:

    POST / HTTP/1.1
    Accept: text/html, application/xhtml+xml, */*
    Accept-Language: en-US,en;q=0.5
    User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; MASAJS; WebView/2.0; rv:11.0) like Gecko
    Accept-Encoding: gzip, deflate
    Host: localhost
    Content-Length: 31
    Connection: Keep-Alive
    Cache-Control: no-cache
    
    user_id=Chinese&session_id=food
    

    POST with WebView in Windows 8

    For Windows 8, do it with JavaScript!

    1. Create a <form>, set the action to your destination URI and set the method to POST.
    2. Add two <input> and name them with the names you want, in this case user_id and session_id.
    3. Add a script that sets the inputs value and submit the form.

    E.g.:

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        webView.NavigateToString(@"<html>
        <head>
            <script type='text/javascript'>
                function doSomething(userIdValue, sessionIdValue) 
                { 
                    document.getElementById('user_id').value = userIdValue;
                    document.getElementById('session_id').value = sessionIdValue;
                    document.getElementById('myForm').submit();
                    return 'Hello World!'; 
                }
            </script>
        </head>
        <body>
            <form id='myForm' action='http://localhost' method='post'>
                <input type='hidden' id='user_id' name='user_id' />
                <input type='hidden' id='session_id' name='session_id' />
            </form>
        </body>
    </html>");
    }
    
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        string result = webView.InvokeScript("doSomething", new string[] { "Chinese", "food" });
    }
    

    That would send a request like this:

    POST / HTTP/1.1
    Accept: text/html, application/xhtml+xml, */*
    Accept-Language: en-US,en;q=0.5
    User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; Touch; MASAJS; WebView/1.0)
    Content-Type: application/x-www-form-urlencoded
    Accept-Encoding: gzip, deflate
    Host: localhost
    Content-Length: 31
    Connection: Keep-Alive
    Cache-Control: no-cache
    
    user_id=Chinese&session_id=food