HttpWebRequest throws unexpected exception.

G

Guest

I am trying to create an assynchronous relay to an external site which is
processing requests slowly. I am using the HttpWebRequest methods to try and
send data asynchronously from a ashx page but am getting a Cast Invalid
exception as follows:

System.InvalidCastException was unhandled by user code
Message="Unable to cast object of type 'System.Net.HttpWebResponse' to
type 'System.Exception'."
Source="System"
StackTrace:
at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult
asyncResult)
at Handler.ReadFirstCallback(IAsyncResult result) in
c:\inetpub\wwwroot\RequestForward\Handler.ashx:line 36
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at
System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state)
at System.Net.ContextAwareResult.Complete(IntPtr userToken)
at System.Net.HttpWebRequest.ProcessResponse()

I cannot understand where this is being thrown as it appears to be coming
from inside the framework. Doing the same call synchronously works fine. Is
it just not possible to use the Async methods inside an ashx page?

System: VS2005 IIS7 in classic pipeline mode.

Code executed up to this point:
private struct stateObj
{
public byte[] data;
public HttpWebRequest req;
}
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
HttpWebRequest req =
(System.Net.HttpWebRequest)WebRequest.Create("http://localhost/RequestForward/Default.aspx");
byte[] ar = context.Request.BinaryRead(context.Request.ContentLength);
stateObj state;
state.req = req;
state.data = ar;
req.ContentLength = ar.Length;
req.Method = "POST";
req.BeginGetResponse(new AsyncCallback(ReadFirstCallback), state);

}

private static void ReadFirstCallback(IAsyncResult result)
{
stateObj state = (stateObj)result.AsyncState;
Stream regstream = state.req.EndGetRequestStream(result); //The
error is thrown on this line.
regstream.Write(state.data, 0, state.data.Length);//rest of
processing follows
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top