User27
User27

Reputation: 545

ASP.net variable to hold the value between multiple http requests

What variable should be used to persist its value during multiple http requests?

I am working on a system built in ASP.NET where I need to get data from one http request process it and pass it to the another API request that comes in.

API: example/api/v1/client

Json request 1:

{ 
    name: abc;
    address: test address;
    phone: 123467687;
    type: client;
    cust_id: c123;
}

Json request 2:

{ 
    company: test company;
    type: company;
    cust_id: c123;
}

Api request 1:

if (type == "client")
{
    // code to insert into client table and get clientID from database
    var clientID = get clientID from database // this clientID I need to use in Api request 2 below to update the client in database
}

Api request 2:

if (type == "company")
{ 
    if (cust_id == c123)
        // code to update client details in database using clientID variable in api request 1
}

I tried using session variable but Session["clientid"] is showing an error.

How to use a session variable or HttpContext.Current.Session?

I am getting below error. Can someone help regarding how to create/declare/assign value to a session variable? enter image description here

Upvotes: 0

Views: 39

Answers (1)

Albert D. Kallal
Albert D. Kallal

Reputation: 49039

If you use HttpContext, then the session() values should persist.

Say we have two parts. The first part will ask for a ID, and say then set it server side to be persisted (into session()).

The 2nd part will then make another web method code (a standard web end point api call), and return the value based on the first web method call.

So, we have this markup:

        <h3>Enter Hotel ID - set id to server session</h3>
        <asp:TextBox ID="txtHotelID" runat="server" ClientIDMode="Static"></asp:TextBox>
        <br />
        <asp:Label ID="Label1" runat="server" Text="" ClientIDMode="Static"></asp:Label>
        <br />
        <asp:Button ID="cmdSetID" runat="server" 
            Text="Set ID into Session()"
            cssclass="btn"
            OnClientClick="setid();return false;"
            />
        <br />
        <br />

        <asp:Button ID="cmdGetHotel" runat="server" 
            Text="Get hotel based on id"
            cssclass="btn"
            OnClientClick="gethotel();return false;"
            />
        <br />
        <br />

        <div style="width:30%">

            <h3>Hotel Information</h3>
            <asp:TextBox ID="txtHotel" runat="server" ClientIDMode="Static" CssClass="form-control">
            </asp:TextBox><br />

            <asp:TextBox ID="txtCity" runat="server" ClientIDMode="Static" CssClass="form-control">
            </asp:TextBox><br />

            <asp:TextBox ID="txtDescription" runat="server" ClientIDMode="Static"
                TextMode="MultiLine"
                rows="6"
                CssClass="form-control">
            </asp:TextBox>

        </div>


        <script>

            function setid() {
                var HotelID = $('#txtHotelID').val()
                var mydata = JSON.stringify({ "HotelID": HotelID })

                $.ajax({
                    type: "POST",
                    url: "SimpleTest.aspx/SetHotelID",
                    data: mydata,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function () {
                        $('#Label1').text("Hotel id now set into sesson")

                    },
                    failure: function (rData) {
                        alert("error " + rData.d);
                    }
                });
            }

            function gethotel() {

                $.ajax({
                    type: "POST",
                    url: "SimpleTest.aspx/GetHotel",
                    data: {},
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (d) {
                        var mydata = d.d  // d is a .net (secuirty) thing, and payload is .d
                        $('#txtHotel').val(mydata.HotelName)
                        $('#txtCity').val(mydata.City)
                        $('#txtDescription').val(mydata.Description)
                    },
                    failure: function (rData) {
                        alert("error " + rData.d);
                    }
                });
            }

        </script>

And our server side code is this:

<WebMethod(EnableSession:=True)>
Public Shared Sub SetHotelID(HotelID As Integer)

    HttpContext.Current.Session("HotelID") = HotelID

End Sub


<WebMethod(EnableSession:=True)>
Public Shared Function GetHotel() As Dictionary(Of String, String)

    Dim strSQL As String =
        "SELECT * FROM tblHotels WHERE ID = @ID"

    Dim HotelID As Integer = HttpContext.Current.Session("HotelID")

    Dim cmdSQL As New SqlCommand(strSQL)
    cmdSQL.Parameters.Add("@ID", SqlDbType.Int).Value = HotelID

    Dim dt As DataTable = MyRstP(cmdSQL)

    Dim MyResult As New Dictionary(Of String, String) ' key pair as json

    If dt.Rows.Count > 0 Then
        With dt.Rows(0)
            MyResult.Add("HotelName", .Item("HotelName"))
            MyResult.Add("City", .Item("City"))
            MyResult.Add("Description", .Item("Description"))
        End With
    End If


    Debug.Print("hotel name = " & MyResult("HotelName"))
    Return MyResult

End Function

Keep in mind any web method end point automatic out of the box supports:

REST calls
SOAP (xml) calls
jQuery.AJAX and JSON data.

Hence, we enter a number into the text box, send the value to server, save into session().

Then the 2nd button click calls another web method, and gets a hotel based on that session value. (this is for demo, since of course the first web method call would in practice return the hotel object to client side).

However, as this shows, the session() values do persist.

The result is thus this:

enter image description here

So, above is a proof of concept, and use of HttpContext.Current should provide use of session(), and as such, session() does persist between web calls.

Upvotes: 0

Related Questions