Recently one of the my friends asked about how to create a web request in asp.net to a url outside of project. So I decided to write a small blog post regarding this. This web request can be easily created with httpwebrequest class and you can easily consume the response we are getting from this. This kind of request can be very useful when you are implementing payment gateways or other third party components. Following is a code for it. It is very easy.
using System;Here in the above code you can see I have created a webrequest with system.net name space and then I have typecast that request in HttpWebRequest Class. There are several parameters are available with request like method which HTML submit method you want to use like “Get” or “Post”. After that I have created a object of HTTPResponse and then with the help of stream reader I have print a response we are getting from the URL.
public partial class WebForm1 : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
string url = "http://localhost:1798/WebForm2.aspx";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string response = streamReader.ReadToEnd();
That’s it. It’s very easy. Hope you will find it useful. Stay tuned for more. Happy Programming..Technorati Tags: Request,Response,ASP.NET,POST CodeProject