Unable to access Session state in Web Service through ajax on the client side

I'm facing an issue where the system is generating a new session for each user when I run an ajax query, instead of having just 1 session per user. Strangely, there were no issues when I tested it in debug mode on my computer, but problems arose on the client site in the distributed application.

Here is the ASP page code:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<input id="Text1" type="text" /><br />
<asp:Button ID="btn_ASP" runat="server" onclick="btn_ASP_Click" Text="Asp" />
<input id="btn_JS" type="button" value="JS" onclick="GetUsersList();" /><br />

The ASP button responsible for generating the 'ConnectCount' Session element:

protected void btn_ASP_Click(object sender, EventArgs e)
{
    int count;
    if (HttpContext.Current.Session["ConnectCount"] == null)
        count = 1;
    else
        count = (int)HttpContext.Current.Session["ConnectCount"] + 1;
    HttpContext.Current.Session["ConnectCount"] = count;
    TextBox1.Text = count.ToString();          
}

Code in the Web Service:

[WebMethod(EnableSession = true)]
[ScriptMethod]
public string Get_UsersList2()
{
    int count;
    if (HttpContext.Current.Session["ConnectCount"] == null)
        count = 1;
    else
        count = (int)HttpContext.Current.Session["ConnectCount"] + 1;
    HttpContext.Current.Session["ConnectCount"] = count;
    return count.ToString();
}

Ajax query to the Web Service:

function GetUsersList() {            
    $.ajax({
        url: '/WbSrv_ACTR.asmx/Get_UsersList2',
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: '{}',
        success: function (data, st) {
            if (st == "success") {
                if (data.d != "") {
                    text1.value = data.d;
                }
            }
        },
        error: function () {
            alert("Cannot get list of users");
        }
    });
}

When I conducted the same operations on a server running IIS 7.5:

result: asp = 5, jq = 1 (incorrect)

The server seems to be using a different session, as elements added via the ASP button are missing in the Web Service. However, the SessionID remains the same.

Does anyone have a solution or workaround for this issue?

Web config:

<system.web>
  <compilation debug="true" targetFramework="4.0">
    <assemblies>
      <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </assemblies>
  </compilation>
  <customErrors mode="Off" />
  <authorization>
      <deny users="?" />
  </authorization>
</system.web>
<system.webServer>
    <security>
        <authentication>
            <windowsAuthentication enabled="true" />
            <anonymousAuthentication enabled="false" />
        </authentication>
    </security>
</system.webServer>

Answer №1

It is important to note the correct usage of session in a web service.

Session["ConnectCount"];

The proper method is as follows:

HttpContext.Current.Session["ConnectCount"];

Therefore, your function should be modified to:

    [WebMethod(EnableSession = true)]
    [ScriptMethod]
    public string Get_UsersList2()
    {
        int count;
        if ( HttpContext.Current.Session["ConnectCount"] == null)
            count = 1;
        else
            count = (int) HttpContext.Current.Session["ConnectCount"] + 1;
         HttpContext.Current.Session["ConnectCount"] = count;
        return count.ToString();
    }

For further reference, you can visit:
How can I access session in a webmethod?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Processing the retrieved object from Dropbox API using Node.js and Express

I've been attempting to carry out a simple task like uploading a file to Dropbox. The file uploads successfully, but I'm in need of the response that contains details such as the file name, size, and path. I understand that I'm getting lost ...

I am encountering the ERR_STREAM_WRITE_AFTER_END error in my Node.js API. Does anyone know how to resolve this problem?

When I try to upload a file using the API from the UI, I encounter the following issue. I am interacting with a Node.js API from React.js and then making calls to a public API from the Node.js server. https://i.stack.imgur.com/2th8H.png Node version: 10. ...

What causes RangeError: Maximum call stack size exceeded when Element UI event handlers are triggered?

I'm currently working on setting up a form and validating it with Element UI. Despite closely following the documentation, I am encountering an issue where clicking or typing into the input boxes triggers a RangeError: Maximum call stack size exceeded ...

Node.js - Creating seamless integration between Sequelize model JS and controller TS

Having trouble making my User.js model recognized inside my UserController.ts with sequelize in TypeScript. Edit: Unable to change the file extensions for these files. In the await User.findAll() part, an error occurs when running on the server, stating ...

Unchecking and checking the radio button is necessary in order for it to function properly

Today, I'm puzzled by the odd behavior of my radio buttons in a pixel drawer project. In order for the radio button to function properly, I have to uncheck it and then recheck it. The pixel drawer allows me to change colors and sizes using these radio ...

The Typewriter Effect does not appear alongside the heading

For my portfolio website, I am using React to create a unique typewriter effect showcasing some of my hobbies. Currently, the code is set up like this: "I like to" [hobbies] However, I want it to display like this: "I like to" [h ...

Creating a bold portion of a string

My task involves dynamically creating <p> elements within a div based on the contents of my codeArray, which can vary in size each time. Instead of hard-coding these elements, I have devised the following method: for(i=1;i<codeArray.length;i++) ...

The value of $parent.$index will consistently be 0 in all cases

I am currently dealing with a nested ng-repeat situation where I am attempting to determine the parent's index. Due to the fact that it is being arranged post-process, the standard ng-repeat="(step_index, step) in flow" method is not working for m ...

Developing a unified input element containing numerous fields

After @grateful answered this question, I wanted to elaborate in case it could benefit others... In my project, there's a page called rsetup.php which has some PHP code to access a MySQL database for filling the HTML content of the page. This HTML ge ...

Choose the value of the dynamically changing id with the same name using jQuery

Whenever I choose the id (they all have the same id number which is fetched dynamically), it displays the value of the first id. Here's how I'm trying to implement it, but it doesn't seem to be working: function editdr() { qty = $(thi ...

I've recently delved into the world of JavaScript and am currently working on creating a calculator website. However, I'm facing some challenges in getting it to function

I created a calculator code using HTML, CSS, and JavaScript for a website. However, due to my limited experience with JavaScript coding, I encountered some issues. Currently, I have only implemented the number input part (not operations or deletion), but w ...

Executing a Javascript function repeatedly

Here is a sample JavaScript function: function f1() { alert("HI"); } I have two different locations where I am calling the same JavaScript function: <input type="submit" id="btn1" onclick="f1()"/> <input type="submit" id="btn2" onclick="f1 ...

"Use the data-attribute to dynamically append a child element to the

Here are a couple of divs that look like this: <div id="thisisme" data-order="1"> <div id="thisisme" data-order="2"> I am looking to insert some content into the specific div with data-order = 1. The following Javascript code is what I have t ...

Vertical scroll bar positioned on the left side of a DIV

Can a vertical scroll bar be placed on the left side of a DIV using CSS? What about JavaScript? ...

Using jQuery.post to select and manipulate the target div displaying Google search results

I am trying to implement a custom form and display the results in a specific target DIV ('results') using ajax. However, I am facing difficulties and unable to figure out what is going wrong. Even after referring to this demo (https://api.jquery ...

Tips for limiting the frequency of Angular provider loading instances

I have created a provider (I tried with a controller as well, but got the same results). Here is my code: .provider('socketio', function() { this.socket = io.connect("//localhost); console.log("LISTENING..."); this.$get = function() ...

To prevent flickering when using child flex elements, it's best to use position fixed along with a dynamically updated scrollbar position using Javascript

My navigation component includes a slim banner that should hide upon scroll and a main-nav bar that should stick to the top of the screen and shrink when it does so. I initially looked into using Intersection Observer based on a popular answer found here: ...

Struggling to display Three.js ply file on screen

I'm having trouble displaying my ply file using the three.js webgl_loader_ply example. Even though I can view the object in MeshLab when I open the ply file, it doesn't show up in the three.js example. I've tried various adjustments like zoo ...

Finding documents in MongoDB where the size of an array exceeds 1

Looking to retrieve documents with an array size greater than 1 in my MongoDB collection Here is a snapshot of my collection: { "_id" : ObjectId("5eaaeedd00101108e1123452"), "type" : ["admin","teacher" ...

Is it possible for a kraken.js backend to manipulate the content of a webpage?

Currently using kraken.js, which is an express.js framework, to construct a localized website. Within the header section, there are 3 language options provided as links. FR | EN | DE My goal is to have the link corresponding to the currently set locale ( ...