cdub
cdub

Reputation: 25741

Check if a HttpWebRequest exists in C# .NET

I have the following declared in my code behind:

  private HttpWebRequest req = null;
  private IAsyncResult result = null;

I have a a button click event in my code behind called btnUpload:

 req = (HttpWebRequest)WebRequest.Create(string.Format("{0}{1}", pageUrl.ToString(), arguments));
 req.Method = "GET";

 // Start the asynchronous request.
 result = (IAsyncResult)req.BeginGetResponse(new AsyncCallback(RespCallback), null);

I then have another button click event on the same page and in the code behind called btnSubmit that has:

 if (req == null)

The req is always null. How do I access the req and result variables?

Upvotes: 0

Views: 1002

Answers (3)

Jeremy Smith
Jeremy Smith

Reputation: 1469

If you're performing an async request, you'll only have access to the result in the callback method RespCallback. You'll also need to pass in the original request into the async call get the response. Take the following example:

protected void Page_Load(object sender, EventArgs e)
        {
            HttpWebRequest req;

            req = (HttpWebRequest)WebRequest.Create(string.Format("{0}{1}", pageUrl.ToString(), arguments));
            req.Method = "GET";

            // pass in request so we can retrieve it later
            req.BeginGetResponse(new AsyncCallback(RespCallback), req); 

        }

        void RespCallback(IAsyncResult result)
        {
            HttpWebRequest originalRequest = (HttpWebRequest)result.AsyncState;
            HttpWebResponse response = (HttpWebResponse)originalRequest.EndGetResponse(result);

            // response.GetResponseStream()
        }

Upvotes: 2

Jack0fshad0ws
Jack0fshad0ws

Reputation: 573

the web (programming) is stateless (apart from some artificial webforms UI state maintainted by viewstate), which means if you instantiate object in btnUpload_Click it won't be there in another button event. So you either need to recreate object etc e.g. HttpWebRequest in both buttons' events or store results of btnUpload_Click somewhere (in Session for instance) and access it from btnSubmit_click. Also google for ASP.net page lifecycle.
Hope this helps

Upvotes: 0

Ondrej Tucny
Ondrej Tucny

Reputation: 27974

This is because your Page object instance does not live across multiple HTTP requests. This behavior is by design in ASP.NET.

You should look at the PageAsyncTask class. This blog post may be useful to learn how to use it.

Upvotes: 2

Related Questions