CSharp HttpRequest Example





Http-request

C# HttpRequest Example

In our c# HttpRequest example , we will write some easily understandable code in c# programming language to work on HttpRequest object.
Before beginning anything, we should have some clear idea about the terminology. Here, we are interested about accessing HttpRequest object with c#, but we must have an understanding about HttpRequest object and why it is needed or why do we use it ?
The HttpRequest object is useful in many ways, that require some information collection through the stateless http protocol.
This information is as simple as login and password data or as complex as xml stylesheet based data.
The biggest advantage of using HttpRequest is that ; it is well readable as well as forwarded by almost every port. So , majority of the servers don’t block your request through a firewall or it is firewall friendly.
In the latest versions of asp.net development environments, the namespace for the class HttpRequest is System.Web.
Let’s discuss a simple scenario in which one page is sending/posting the Data (in the form of the QueryString) and the other one is receiving the same data (from Request Object).
We call the sender as Sender.aspx and the receiver as Receiver.aspx pages respectively.

The markup of the Sender.aspx is as follows:


<%@ Page Language="C#" %>

<!DOCTYPE html>
<script runat="server">

    protected void btnSend_Click(object sender, EventArgs e)
    {
        // using response object to send data
        Response.Redirect("Receiver.aspx?myData=1");
    }
</script>


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" Width="105px" />
    
    </div>
    </form>
</body>
</html>
</htmlscript>

The markup of Receiver.aspx is as follows:


<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        // Check if the requested data is not null
        if (Request.QueryString[0] != null)
        {

            lblShow.Text = "The Data is :" + Request.QueryString[0];
        }
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblShow" runat="server" ></asp:Label>
    </div>
    </form>
</body>
</html>