[RESOLVED] problem with webrequest
Hi!
I ahve implemented a simple method that makes a POST to a webserver and return the response. Here is the code:
Code:
public void SendRequest(string baseUrl, string post, string method)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseUrl + method);
request.Method = "POST";
request.ContentType = "message/rfc822";
request.BeginGetRequestStream(ar =>
{
using(var sw = new StreamWriter(request.EndGetRequestStream(ar)))
{
string json = ar.AsyncState.ToString();
sw.Write(json);
sw.Flush();
}
request.BeginGetResponse(aResult =>
{
using (var streamReader = new StreamReader(request.EndGetResponse(aResult).GetResponseStream()))
{
// Throw an event to signal that the request is finished
handleData(streamReader.ReadToEnd());
}
}, null);
}, null);
}
The proglem is that when I call the "string json = ar.AsyncState.ToString();" I get a null exception stating that the AsyncState property is null.
I have tested to make a POST without lambdas, and then it works, so there must be some flaw in the above code, can anyone please help me to find it?
The code that works look like this:
Code:
private void GetRequestCallBack(IAsyncResult aResult)
{
using (StreamWriter streamWriter = new StreamWriter(request.EndGetRequestStream(aResult)))
{
string json = aResult.AsyncState.ToString();
streamWriter.Write(json);
streamWriter.Flush();
}
request.BeginGetResponse(new AsyncCallback(GetResponseCallBack), request);
}
private void GetResponseCallBack(IAsyncResult aResult)
{
using (var streamReader = new StreamReader(request.EndGetResponse(aResult).GetResponseStream()))
{
result = streamReader.ReadToEnd();
// Throw an event to signal that the verification is finished
handleData(result);
}
}
I init it with this call:
Code:
request = (HttpWebRequest)WebRequest.Create(BaseUrl + @"activation/finishActivation");
request.Method = "POST";
request.ContentType = "message/rfc822";
request.BeginGetRequestStream(new AsyncCallback(GetRequestCallBack), smime.MessageHeadersString + Environment.NewLine + smime.Message);
kind regards
Re: problem with webrequest
How can you get the async state if you don't pass anything in?
Code:
request.BeginGetRequestStream(ar =>
{
using(var sw = new StreamWriter(request.EndGetRequestStream(ar)))
{
string json = ar.AsyncState.ToString();
sw.Write(json);
sw.Flush();
}
request.BeginGetResponse(aResult =>
{
using (var streamReader = new StreamReader(request.EndGetResponse(aResult).GetResponseStream()))
{
// Throw an event to signal that the request is finished
handleData(streamReader.ReadToEnd());
}
}, null);
}, null); //<--This null is what is passed into the AsyncState of the AsyncResult
}
The bolded null is the state that gets passed to the callback but you make it null so when you try to access the AsyncState, it will always be null. Same applied to the BeginGetResponse method if you use it.
Re: problem with webrequest
yes you are correct,I missed that.Lol.Thanks for the assistance!!
/Henrik