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.
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
namespace Experiment
{
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();
Response.Write(Response);
}
}
}
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
Thanks for sharing this code, I was in search of this code since from long time. Now I would like to try to practically implement this.
ReplyDeleteyour site makes 100% CPU usage ... reconsider your theme and scripts ...
ReplyDeleteCan you tell How to create a social account from out website using ASP.net
ReplyDeleteIt is very help full thanks
ReplyDelete