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. 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.
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: