I am bit confused in using httpwebrequest. I tried to look into some articles but not able to get much from it as I am doing it for the first time. Below is the code I am trying to work on and I have few questions,
a) The ASPX page has few controls defined and in code-behind I create few controls. When I do httpwebrequest with POST, do I need to consider all controls and their values? I need to do POST for one of the controls only. Can I do it only for that control?
b) What URL should be specified in “(HttpWebRequest)WebRequest.Create”? I assume it is the same page that is shown to the user. For example in my example below it is (“http://localhost/MyIdentity/Confirm.aspx?ID=New&Designer=True&Colors=Yes”);
c) Is there anything else I need to modify or take care of either in markup or code to achieve httpwebrequest?
private void OnPostInfoClick(object sender, System.EventArgs e)
{
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = ""; //Read from the stored array and print each element from the array loop here.
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http://localhost/MyIdentity/Confirm.aspx?ID=New&Designer=True&Colors=Yes");
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
}
You typically would only use it for server-to-server communication (not necessarily for page to page data transfer).
If I’m understanding your post and question correctly, you just seem to want to send POST data to some other page in your ASP.Net application. If so, one way you can do that is to simply change the
PostBackUrlof your submit button (form target) instead of the normal Postback (to same page).There are other ways, but this should be the simplest.
In the above, instead of POSTing back to itself, the POST will be sent to
foo.aspxwhere you can examine/use/process the POSTed data.Update based on your comment:
You don’t have to code your way through HttpWebRequest for that. The normal ASP.net WebForms model does it for you.
Given this simple ASP.net web Forms page:
Your inline or code behind would look something like this: