I donβt see what is wrong with your code (maybe a complete example of what you are trying to do can help), but here is a simple working example of how to perform the action you want to do.
It sends some data to the URI and then passes the response to the callback function:
Just do it (using BackgroundWorker is optional, but recommended)
var bw = new BackgroundWorker(); bw.DoWork += (o, args) => PostDataToWebService("http://example.com/something", "key=value&key2=value2", MyCallback); bw.RunWorkerAsync();
Here's the callback function to which it refers:
(You can change this, but it fits your needs.)
public static void MyCallback(string aString, Exception e) { Deployment.Current.Dispatcher.BeginInvoke(() => { if (e == null) { // aString is the response from the web server MessageBox.Show(aString, "success", MessageBoxButton.OK); } else { MessageBox.Show(e.Message, "error", MessageBoxButton.OK); } }); }
Here is the actual method:
public void PostDataToWebService(string url, string data, Action<string, Exception> callback) { if (callback == null) { throw new Exception("callback may not be null"); } try { var uri = new Uri(url, UriKind.Absolute); var req = HttpWebRequest.CreateHttp(uri); req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; AsyncCallback GetTheResponse = ar => { try { var result = ar.GetResponseAsString(); callback(result, null); } catch (Exception ex) { callback(null, ex); } }; AsyncCallback SetTheBodyOfTheRequest = ar => { var request = ar.SetRequestBody(data); request.BeginGetResponse(GetTheResponse, request); }; req.BeginGetRequestStream(SetTheBodyOfTheRequest, req); } catch (Exception ex) { callback(null, ex); } }
and extension / helper methods are used here:
public static class IAsyncResultExtensions { public static string GetResponseAsString(this IAsyncResult asyncResult) { string responseString; var request = (HttpWebRequest)asyncResult.AsyncState; using (var resp = (HttpWebResponse)request.EndGetResponse(asyncResult)) { using (var streamResponse = resp.GetResponseStream()) { using (var streamRead = new StreamReader(streamResponse)) { responseString = streamRead.ReadToEnd(); } } } return responseString; } public static HttpWebRequest SetRequestBody(this IAsyncResult asyncResult, string body) { var request = (HttpWebRequest)asyncResult.AsyncState; using (var postStream = request.EndGetRequestStream(asyncResult)) { using (var memStream = new MemoryStream()) { var content = body; var bytes = System.Text.Encoding.UTF8.GetBytes(content); memStream.Write(bytes, 0, bytes.Length); memStream.Position = 0; var tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); postStream.Write(tempBuffer, 0, tempBuffer.Length); } } return request; } }