locked
Set Custom Request Header and Retrieve the Same Value in the Response RRS feed

  • Question

  • User-380050312 posted

    I have a requirement like, i need to append a value to every request sent from each page & i want to retrieve the value from the other end.

    For Example:

    I am in Page A now. On load of this Page A, i will generate a random number  & that number needs to be appended to the request i made from this Page A. means, from Page A i am navigating to Page B. I need to pass a value from Page A to Page B through the Request / Response headers.

    How do i achieve this ?

    Sunday, May 3, 2015 7:20 AM

Answers

  • User281315223 posted

    There are a variety of methods for handling passing data across from one page to another and none of them is necessary going to be "better" than the other and will vary on the situation : 

    • Using the Session
    • Using QueryString Parameters
    • Using Cookies
    • Using Cache
    • Using Forms
    • Using Request Headers

    I'll provide examples of each of these approaches below including your specific requirement :

    Using the Session

    The Session would work nearly exactly the same and functions as an application-wide collection that you can store values in. You just need to store the values prior to your Redirect and access them afterwards : 

    // Your values to pass across
    Session["A"] = YourTextBox.Text;
    Session["B"] = YourOtherTextBox.Text;
    
    // Perform your Redirect
    Response.Redirect("YourTargetPage.aspx");

    and within your target page, simply check if the values exist in the Session and grab them by their key : 

    // Check if your values exist in the Session
    if(Session["A"] != null && Session["B"] != null)
    {
         // Grab your values
         string valueA = Session["A"];
         string valueB = Session["B"];
    
         //Use your values here
    }

    Using QueryString Parameters

    QueryString parameters are actually incredibly helpful and allow you handle and pass data to a specific page before the page is ever loaded. They are fairly straight forward (Key1=Value1&Key2=Value2) so there wouldnt be that much room for overly simplifying it. You simply need to just include the URL followed by a '?' to indicate the beginning of the QueryString and then seperate each of the values using ampersands '&' :

    YourPage.aspx?Key1=Value1&Key2=Value2

    or for a full URL : 

    http://www.yourdomain.com/YourPage.aspx?Key1=Value1&Key2=Value2

    This would navigate to your YourPage.aspx page and you could easily use the Keys and Values from the QueryString (if they are available) through the Request.QueryString collection : 

    // If the "Key1" QueryString key is available
    if(!String.IsNullOrEmpty(Request.QueryString["Key1"]))
    {
         //Access the value ("Value1")
         var key1 = Request.QueryString["Key1"];
    }

    You can apply this same example to a situation that would populate a TextBox as well : 

    http://www.yourdomain.com/YourPage.aspx?TextBox1=HelloWorld

    and then if the Key exists, set the Text property accordingly : 

    //If a TextBox1 key exists - then set your TextBox.Text property
    if(!String.IsNullOrEmpty(Request.QueryString["TextBox1"]))
    {
         //Sets your Textbox to "HelloWorld"
         TextBox1.Text = Request.QueryString["TextBox1"];
    }

    So for example if you wanted to pass several values from your Test.aspx page to your Main.aspx page, you could use : 

    // Example variables
    string a = "Variable A"
    string b = "Variable B";
    
    // Send those values to your Main.aspx page
    Response.Redirect(String.Format("Main.aspx?a={0}&b={1}",a,b));

    Using Cookies

    A Cookie can often be a solid option to store values in if you need the values to persist for extended periods of time. Cookies are stored at the application-level and would persist across different pages and even if you closed the browser and later returned to a specific page. This is how ASP.NET traditionally handles authentication (e.g. when a user logs in, they stay logged in).

    // Create a cookie that contains a value that will be held for 7 days
    HttpCookie cookie = new HttpCookie("Delicious");
    cookie.Value = "This is an example cookie.";
    cookie.Expires = DateTime.Now.AddDays(7);
    Response.Cookies.Add(cookie);

    Then you can just check for the existence of the cookie within any area of your application after it has been created in a method similar to the following to retrieve the values in it :

    // Attempt to retrieve your cookie
    HttpCookie cookie = Request.Cookies.Get("Delicious");
    
    // Check if the cookie exists
    if(cookie != null)
    {
           // It exists, so use it's value in a query via cookie.Value
           var cookieMessage = cookie.Value; // yields "This is an example cookie."
    }
    else
    {
           // No cookie was available, do something here
    }

    Using Cache

    The Cache works in a fashion that is nearly identical to the Session, however it is not handled at the User-level but rather the Application-level. This is an extremely important difference because this means that all of your users will share the same Cache variables (e.g. if one user sets it, another can change it).

    // Your values to pass across
    Cache["A"] = YourTextBox.Text;
    Cache["B"] = YourOtherTextBox.Text;
    
    // Perform your Redirect
    Response.Redirect("YourTargetPage.aspx");

    and within your target page, simply check if the values exist in the Session and grab them by their key : 

    // Check if your values exist in the Cache
    if(Cache["A"] != null && Cache["B"] != null)
    {
         // Grab your values
         string valueA = Cache["A"];
         string valueB = Cache["B"];
    
         // Use your values here
    }

    Using Forms

    One of the easiest may be to actually use a Form, which would allow you to basically pass the entire collection of values from one page to the next.

    You would just need to set the target on your form to your next page, which is handled through the PostBackUrl property of your submit button and you could access the values from the previous page using the Request.Form object as seen below : 

    InitialPage.aspx

    In this page you will just need a single form that will store your values and post them to the target which is specified in the PostBackUrl property of your Submit Button.

    <!-- Notice the Action attribute pointing to your other page -->
    <form id="form1" runat="server">
         <asp:TextBox ID="FirstName" runat="server"></asp:TextBox>
         <asp:TextBox ID="LastName" runat="server"></asp:TextBox>
         <!-- Other properties here -->
         <asp:Button ID="SubmitButton" runat="server" Text="Submit" PostBackUrl="Details.aspx" />
    </form>

    Details.aspx

    You can have these values appear within your Details page as well and then within the code-behind after the initial values are posted, you will be able to set them accordingly : 

    <!-- Your Details Page -->
    <form id="form1" runat="server"> 
            <!-- These properties will be set within your Page_Load event of your Details Page -->
            <asp:TextBox ID="FirstName" runat="server" />
            <asp:TextBox ID="LastName" runat="server" />
            <!-- Additional Fields -->
    </form>

    Details.aspx Code-Behind

    So within the code-behind, you'll access the values that were posted to your Details Page :

    protected void Page_Load(object sender, EventArgs e)
    {
          //If values were posted from your other page - populate their corresponding textboxes
          FirstName.Text = Request.Form["FirstName"];
          LastName.Text = Request.Form["LastName"];
    
          //Populate other values here
    }

    Using Request Headers

    Much like the previous approaches, you can store a value within the current Request such that it will be accessible within the Response. This is going to work similar to many of the other approaches mentioned earlier, just the syntax will be slightly different.

    Let's say within your PageA.aspx page, you decide to generate a random value and store it within a custom header :

    // Add a custom value to the Request (in this case a random number)
    Response.AddHeader("YourRandomValue", new Random(DateTime.Now.Ticks).Next().ToString());
    // Redirect to your other page
    Response.Redirect("PageB.aspx");

    This will add the random value (a non-negative integer) to your Response within PageB by simply checking the appropriate header value :

    // Ensure the header exists
    if(Request.Headers["YourRandomValue"] != null)
    {
        // It does exist, so parse it's value (as an integer if you need it)
        int passedValue = Convert.ToInt32(Reqeuest.Headers["YourRandomValue"]);
    }
    else
    {
        // Otherwise no value was present within the header, handle accordingly
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, May 3, 2015 8:33 AM
  • User1644755831 posted

    Hello Ganesh2890,

    You could probably try to achieve this using query string tokens and cookies. you just need to define a solid logic that will give you this.

    From Home.aspx page,  I will go to PageA.aspx in a new tab, on page load of PageA.aspx I will get a value that is 10

    1. Pass a unique token id with value 10 when you do this. store them on cookies.

    Again from the home.aspx page, I will open PageA.aspx in another new tab, this time i will get a new value that is 20.

    2. Pass a unique token id with value 10 when you do this. store them on cookies.

    PageA has a link which will redirect to PageC.aspx. (Note:  It  need not be a server side control. I can be an Anchor tag.  ) Now if i Click the link from the First tab, It will open PageC.aspx. on page load of Pagec.aspx i should get 10.

    3. you will get token id from request.Querystring and using that get the value 10 and pass to the page C.aspx. in query string so you will get it on page load.

    If the link in the second tab was clicked, on page load of the PageC.aspx i should get 20.

    4. if second tab link is clicked do same as above and get 20 from cookie and pass that as querystring to pageC.aspx

    Hope I am clear enough and you understand. you can mix @Rion's techniques and achieve this easily the main core logic is that you can pass token id in query string to uniquely identify  the tab page.

    Hope this helps.

    With Regards,

    Krunal Parekh

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 6, 2015 2:43 AM

All replies

  • User281315223 posted

    There are a variety of methods for handling passing data across from one page to another and none of them is necessary going to be "better" than the other and will vary on the situation : 

    • Using the Session
    • Using QueryString Parameters
    • Using Cookies
    • Using Cache
    • Using Forms
    • Using Request Headers

    I'll provide examples of each of these approaches below including your specific requirement :

    Using the Session

    The Session would work nearly exactly the same and functions as an application-wide collection that you can store values in. You just need to store the values prior to your Redirect and access them afterwards : 

    // Your values to pass across
    Session["A"] = YourTextBox.Text;
    Session["B"] = YourOtherTextBox.Text;
    
    // Perform your Redirect
    Response.Redirect("YourTargetPage.aspx");

    and within your target page, simply check if the values exist in the Session and grab them by their key : 

    // Check if your values exist in the Session
    if(Session["A"] != null && Session["B"] != null)
    {
         // Grab your values
         string valueA = Session["A"];
         string valueB = Session["B"];
    
         //Use your values here
    }

    Using QueryString Parameters

    QueryString parameters are actually incredibly helpful and allow you handle and pass data to a specific page before the page is ever loaded. They are fairly straight forward (Key1=Value1&Key2=Value2) so there wouldnt be that much room for overly simplifying it. You simply need to just include the URL followed by a '?' to indicate the beginning of the QueryString and then seperate each of the values using ampersands '&' :

    YourPage.aspx?Key1=Value1&Key2=Value2

    or for a full URL : 

    http://www.yourdomain.com/YourPage.aspx?Key1=Value1&Key2=Value2

    This would navigate to your YourPage.aspx page and you could easily use the Keys and Values from the QueryString (if they are available) through the Request.QueryString collection : 

    // If the "Key1" QueryString key is available
    if(!String.IsNullOrEmpty(Request.QueryString["Key1"]))
    {
         //Access the value ("Value1")
         var key1 = Request.QueryString["Key1"];
    }

    You can apply this same example to a situation that would populate a TextBox as well : 

    http://www.yourdomain.com/YourPage.aspx?TextBox1=HelloWorld

    and then if the Key exists, set the Text property accordingly : 

    //If a TextBox1 key exists - then set your TextBox.Text property
    if(!String.IsNullOrEmpty(Request.QueryString["TextBox1"]))
    {
         //Sets your Textbox to "HelloWorld"
         TextBox1.Text = Request.QueryString["TextBox1"];
    }

    So for example if you wanted to pass several values from your Test.aspx page to your Main.aspx page, you could use : 

    // Example variables
    string a = "Variable A"
    string b = "Variable B";
    
    // Send those values to your Main.aspx page
    Response.Redirect(String.Format("Main.aspx?a={0}&b={1}",a,b));

    Using Cookies

    A Cookie can often be a solid option to store values in if you need the values to persist for extended periods of time. Cookies are stored at the application-level and would persist across different pages and even if you closed the browser and later returned to a specific page. This is how ASP.NET traditionally handles authentication (e.g. when a user logs in, they stay logged in).

    // Create a cookie that contains a value that will be held for 7 days
    HttpCookie cookie = new HttpCookie("Delicious");
    cookie.Value = "This is an example cookie.";
    cookie.Expires = DateTime.Now.AddDays(7);
    Response.Cookies.Add(cookie);

    Then you can just check for the existence of the cookie within any area of your application after it has been created in a method similar to the following to retrieve the values in it :

    // Attempt to retrieve your cookie
    HttpCookie cookie = Request.Cookies.Get("Delicious");
    
    // Check if the cookie exists
    if(cookie != null)
    {
           // It exists, so use it's value in a query via cookie.Value
           var cookieMessage = cookie.Value; // yields "This is an example cookie."
    }
    else
    {
           // No cookie was available, do something here
    }

    Using Cache

    The Cache works in a fashion that is nearly identical to the Session, however it is not handled at the User-level but rather the Application-level. This is an extremely important difference because this means that all of your users will share the same Cache variables (e.g. if one user sets it, another can change it).

    // Your values to pass across
    Cache["A"] = YourTextBox.Text;
    Cache["B"] = YourOtherTextBox.Text;
    
    // Perform your Redirect
    Response.Redirect("YourTargetPage.aspx");

    and within your target page, simply check if the values exist in the Session and grab them by their key : 

    // Check if your values exist in the Cache
    if(Cache["A"] != null && Cache["B"] != null)
    {
         // Grab your values
         string valueA = Cache["A"];
         string valueB = Cache["B"];
    
         // Use your values here
    }

    Using Forms

    One of the easiest may be to actually use a Form, which would allow you to basically pass the entire collection of values from one page to the next.

    You would just need to set the target on your form to your next page, which is handled through the PostBackUrl property of your submit button and you could access the values from the previous page using the Request.Form object as seen below : 

    InitialPage.aspx

    In this page you will just need a single form that will store your values and post them to the target which is specified in the PostBackUrl property of your Submit Button.

    <!-- Notice the Action attribute pointing to your other page -->
    <form id="form1" runat="server">
         <asp:TextBox ID="FirstName" runat="server"></asp:TextBox>
         <asp:TextBox ID="LastName" runat="server"></asp:TextBox>
         <!-- Other properties here -->
         <asp:Button ID="SubmitButton" runat="server" Text="Submit" PostBackUrl="Details.aspx" />
    </form>

    Details.aspx

    You can have these values appear within your Details page as well and then within the code-behind after the initial values are posted, you will be able to set them accordingly : 

    <!-- Your Details Page -->
    <form id="form1" runat="server"> 
            <!-- These properties will be set within your Page_Load event of your Details Page -->
            <asp:TextBox ID="FirstName" runat="server" />
            <asp:TextBox ID="LastName" runat="server" />
            <!-- Additional Fields -->
    </form>

    Details.aspx Code-Behind

    So within the code-behind, you'll access the values that were posted to your Details Page :

    protected void Page_Load(object sender, EventArgs e)
    {
          //If values were posted from your other page - populate their corresponding textboxes
          FirstName.Text = Request.Form["FirstName"];
          LastName.Text = Request.Form["LastName"];
    
          //Populate other values here
    }

    Using Request Headers

    Much like the previous approaches, you can store a value within the current Request such that it will be accessible within the Response. This is going to work similar to many of the other approaches mentioned earlier, just the syntax will be slightly different.

    Let's say within your PageA.aspx page, you decide to generate a random value and store it within a custom header :

    // Add a custom value to the Request (in this case a random number)
    Response.AddHeader("YourRandomValue", new Random(DateTime.Now.Ticks).Next().ToString());
    // Redirect to your other page
    Response.Redirect("PageB.aspx");

    This will add the random value (a non-negative integer) to your Response within PageB by simply checking the appropriate header value :

    // Ensure the header exists
    if(Request.Headers["YourRandomValue"] != null)
    {
        // It does exist, so parse it's value (as an integer if you need it)
        int passedValue = Convert.ToInt32(Reqeuest.Headers["YourRandomValue"]);
    }
    else
    {
        // Otherwise no value was present within the header, handle accordingly
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, May 3, 2015 8:33 AM
  • User-380050312 posted

    Thanks for your detailed information. But this solution will not solve my problem.  Please look at the below image.

    From Home.aspx page,  I will go to PageA.aspx in a new tab, on page load of PageA.aspx I will get a value that is 10. Again from the home.aspx page, I will open PageA.aspx in another new tab, this time i will get a new value that is 20.  So now i have 2 tabs. 1st tab i have PageA.aspx with id 10, and in the 2nd tab i have the PageA.aspx page with id 20. Assume that both values are stored in a hidden field.

    PageA has a link which will redirect to PageC.aspx. (Note:  It  need not be a server side control. I can be an Anchor tag.  ) Now if i Click the link from the First tab, It will open PageC.aspx. on page load of Pagec.aspx i should get 10. If the link in the second tab was clicked, on page load of the PageC.aspx i should get 20.

    Hope you can understand the problem.

    Sunday, May 3, 2015 9:20 AM
  • User475983607 posted

    For your scenario, the header must be created in the client.  Therefore, you'll need to create a JavaScript/JQuery framework that adds this special value to the request when a link or button is clicked.   On the server you'll need another framework that handles the special value. 

    Take a look at how the AntiForgeryToken in MVC works.  That should give you some ideas.

    Otherwise, use cookies.  You'll still need to create a framework on the server though.

    Tuesday, May 5, 2015 1:54 PM
  • User1644755831 posted

    Hello Ganesh2890,

    You could probably try to achieve this using query string tokens and cookies. you just need to define a solid logic that will give you this.

    From Home.aspx page,  I will go to PageA.aspx in a new tab, on page load of PageA.aspx I will get a value that is 10

    1. Pass a unique token id with value 10 when you do this. store them on cookies.

    Again from the home.aspx page, I will open PageA.aspx in another new tab, this time i will get a new value that is 20.

    2. Pass a unique token id with value 10 when you do this. store them on cookies.

    PageA has a link which will redirect to PageC.aspx. (Note:  It  need not be a server side control. I can be an Anchor tag.  ) Now if i Click the link from the First tab, It will open PageC.aspx. on page load of Pagec.aspx i should get 10.

    3. you will get token id from request.Querystring and using that get the value 10 and pass to the page C.aspx. in query string so you will get it on page load.

    If the link in the second tab was clicked, on page load of the PageC.aspx i should get 20.

    4. if second tab link is clicked do same as above and get 20 from cookie and pass that as querystring to pageC.aspx

    Hope I am clear enough and you understand. you can mix @Rion's techniques and achieve this easily the main core logic is that you can pass token id in query string to uniquely identify  the tab page.

    Hope this helps.

    With Regards,

    Krunal Parekh

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 6, 2015 2:43 AM