0

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

3
  • Which version of net-framework och .net do you use? Commented Jan 3 at 7:41
  • I am using framework 4.6 Commented Jan 3 at 17:48
  • I have edited the question, I am getting NullReferenceException while trying to assign value to a session variable, pls help to resolve this error Commented Jan 3 at 17:54

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have edited the question, I am getting NullReferenceException while trying to assign value to a session variable, pls help to resolve this error
You now been asked multiple times to share a 100% complete example in which we can reproduce this error. Without providing a "minimal" and reproducible example, we really have next to nothing to go on here. I assume you have [WebMethod(EnableSession = true)] for the web method define? We can't see enough code to reproduce, so all we can do is play ask 100+ more questions. If you keep this up, I going to suggest you try truck driving school, maybe restaurant management school, or maybe auto repair school. This is NOT how troubleshooting software works. Provide a full working test example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.