Calling WCF REST Services with Basic authentication from Windows Phone 7


Today while working I came across a requirement to consume a REST Service. To consume REST Service application had to provide username and password. Initially I thought it should be easier task and I tried consuming REST Service as below:

    WebClient proxy = new WebClient();
    NetworkCredential credential = new NetworkCredential("username", "password");
    proxy.Credentials = credential;
    proxy.DownloadStringCompleted += new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
    proxy.DownloadStringAsync(new Uri("http://localhost:2572/Service1.svc/GetStudents"));
 

In the completed event accessing the returned data is below,  

    void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        string result = e.Result;
        MessageBox.Show(result);
    }


When I tried running application I got below exception.

windowsphone.gif

The WebClient is the main reason behind the above exception. WebClient is unable to pass credentials to the service. Better approach to call REST Service with Basic authentication is to use HttpWebRequest class.

    HttpWebRequest client = (WebRequest.CreateHttp(new Uri("http://localhost:2572/Service1.svc/GetStudents"))) as HttpWebRequest;
    NetworkCredential cred = new NetworkCredential("username", "password");
    client.Credentials = cred;
    var result = (IAsyncResult)client.BeginGetResponse(ResponseCallback, client);
    MessageBox.Show(responseData);

And in Responsecallback method parse result as below. In this case I am calling the service on different thread.

    private void ResponseCallback(IAsyncResult result)
    {
        var request = (HttpWebRequest)result.AsyncState;
        var response = request.EndGetResponse(result);
        using (var stream = response.GetResponseStream())
        using (var reader = new StreamReader(stream))
        {                
            var contents = reader.ReadToEnd();
            Dispatcher.BeginInvoke(() => { responseData = contents; });
        }
    }


You should be using HttpWebRequest to consume the REST Service with Basic authentication. I hope this post is useful. Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all