Is there a way to retrieve a string using the HTTP session in JavaScript?

I am currently developing a chat application using web API ASP.NET with C# in VS Code. The user registration and login functionalities are working seamlessly with the database. I have integrated the SignalR sample code into the Welcome page, but I have a specific requirement: the username displayed should be the logged-in user's username, and when I click on "Send Message", it should show as follows: "acc1 says hello world".

VIEW SCREENSHOT OF MY PAGE

https://i.sstatic.net/DePtN.png The functionality of the "Send Message" button is defined in the "chat.js" file, and I'm facing an issue where I cannot retrieve the "username" string within the JavaScript code. Using

HttpContext.Session.GetString("username")
does not work in JavaScript.

chat.js

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;



connection.on("ReceiveMessage", function (user, message) {
    var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    var encodedMsg = user + " says " + msg;
    var li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("messagesList").appendChild(li);
});

connection.start().then(function () {
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    connection.invoke("SendMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});

Welcome.cshtml

@page
@model probagetrequest.Pages.WilcomeModel
@using Microsoft.AspNetCore.Http

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Welcome</title>
</head>
<body>

    Welcome @HttpContext.Session.GetString("username")
    <br>
    <br>
    <a asp-page="index" asp-page-handler="logout">Logout</a>
    <a asp-page="profile">Change Profile</a>

    <div class="container">
        <div class="row"> </div>
        <div class="row">
            <div class="col-2">User</div>
            <div class="col-4"><input type="text" id="userInput" /></div>
        </div>
        <div class="row">
            <div class="col-2">Message</div>
            <div class="col-4"><input type="text" id="messageInput" /></div>
        </div>
        <div class="row"> </div>
        <div class="row">
            <div class="col-6">
                <input type="button" id="sendButton" value="Send Message" />
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-12">
            <hr />
        </div>
    </div>
    <div class="row">
        <div class="col-6">
            <ul id="messagesList"></ul>
        </div>
    </div>

    <script src="~/js/signalr/dist/browser/signalr.js"></script>
    <script src="~/js/chat.js"></script>

</body>
</html>

ChatHub.cs

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
using System;

namespace SignalRChat.Hubs
{
    public class ChatHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            Console.WriteLine($"user={user}, message={message}");
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}

Answer №1

To retrieve the username from the session in ASP.NET, you can use the following code snippet:

var user = '@HttpContext.Session.GetString("username")';
. You can then utilize the 'user' object as needed.

If your script is located in a separate file, you can assign the value to the global window object and access it in your JavaScript file.

window.user = '@HttpContext.Session.GetString("username")';

<script>
   var user = '@HttpContext.Session.GetString("username")'; //or window.user
   console.log(user)
</script>

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

Generating a new array in NodeJs from data retrieved by querying MySQL

In my NodeJs project, I am trying to generate a new array from the results of a MySQL query. Here is the current result: [ { "availabilityId": 1, "dayName": 1, "fromTime": "05:30:00", "toTime": "10:00:00" }, { ...

Combining C# RegEx to match the start of a string and the start of a word at

Let's imagine we have a total of six strings: "abcd bbb ccc" "abce bbb ccc" "abcf bbb ccc" "aaa abcd ccc" "aaa abce ccc" "aaa abcf ccc" When a user enters the expression "<abc[!e]", It is translated into the regex: "^abc[^e]". This transla ...

Understanding the difference between Parameters in Javascript and Java

Currently, I am facing an issue where I am losing some information while sending an ajax request to a servlet. The specific parameter that I am losing data from is the "comment" parameter. Below are the last 4 lines of my ajax code: var params = "name=" + ...

OpenStreetMap is failing to display the full map within the designated div

Here is the code snippet for displaying a map when clicking on a Span text, but not showing it in full: var latitude = document.querySelector('#lati').value; var longitude = document.querySelector('#longi').value; var open_address = doc ...

Unlocking the hidden value with Python Selenium from an unselectable element

I am attempting to retrieve a value of 570 using Python Selenium. ... <div _ngcontent-lci-c225="" class="mr-4 bd-highlight"> <span _ngcontent-lci-c225="" class="clickable ng-star-inserted" style="ma ...

Guide on extracting a particular segment of JSON data and converting it to a string

Recently, I started delving into JSON, node.js, and JavaScript. My small node.js server pulls a JSON object (referred to as weatherData below) from openweathermap.org. My goal is to only display a specific part of the JSON object – the "temp" section. Cu ...

Close the material-ui popper when clicking away

I am currently working on implementing a Material UI popper feature that should close when the user clicks outside of it using ClickAwayListener. However, I have been unable to make this functionality work despite trying different approaches. I've att ...

When the button is clicked, dynamically fetch data from a MySQL database using PHP without the need to refresh

I have a .php page where I am displaying a table from my MySQL database using PHP based on a cookie value. On this same page, I have implemented a feature that allows me to change the cookie data without having to reload the entire page by simply clicking ...

Loading a Dropdown Menu with Database Data

My journey with JSON data and ajax is just starting, and I'm eager to populate a Select List from a web service. After using Fiddler to confirm that the web service is indeed returning JSON data correctly, I proceeded to verify it. However, the select ...

Could use some help with configuring express routes with parameters

Greetings! I am new to working with Express and I am currently in the process of creating a portfolio website. In my project, I have a Pug file named project.pug which includes HTML content that should dynamically render based on the ID of each project sto ...

The two-dimensional array in JavaScript has not been defined

I've been trying to troubleshoot the error in my code with no success. I have a simple example of what I believe to be a two-dimensional array, but I keep getting an undefined error. var city = 'London', country = 'England'; ...

Using Multer: Specifying multiple destinations with the destination property

I am facing a situation where I have to store images in multiple directories. To achieve this, I have configured multer as follows: app.use(multer({ dest: path.join(__dirname, '`public/assets/img/profile`'), rename: function (fieldname, ...

Steps to obtain the original video file from a Google Drive link for embedding on a website

I have a video stored on Google Drive with a link that is supposed to provide the raw video file. However, when I click on the link, I am directed to an image instead. https://drive.google.com/uc?id=xxx How can I obtain the correct playable link to use th ...

tips for integrating html5 elements with django forms

I am interested in utilizing the following code: # extra.py in yourproject/app/ from django.db.models import FileField from django.forms import forms from django.template.defaultfilters import filesizeformat from django.utils.translation import ugettext_ ...

Bypassing 403 error in redux and react application

It appears that Redux or express is failing to handle an error scenario where a user updates their password using a reset password link token. https://i.sstatic.net/uo7ho.png https://i.sstatic.net/WGHdt.png An error message should be displayed as follow ...

There was an error of "Uncaught TypeError: CANNON.NaiveBroadPhase is not a constructor"

I've been diving into cannon.js and encountering the following error: Uncaught TypeError: CANNON.NaiveBroadPhase is not a constructor. I've tried numerous solutions but none seem to be working. Here's a snippet of my script: var scene, came ...

Can a JavaScript file be imported exclusively for a Vue component?

When attempting to utilize the table component in the vue-ant framework, I am facing an issue. I am only looking to import the table style, but when I try to import the table style using import 'ant-design-vue/lib/table/style/css', it affects all ...

Angular - Incorporating Query Parameters into URL

For instance, let's say I have the following URL: http://local.com/. When I invoke the function in my SearchController, I aim to set text=searchtext and generate a URL like this: http://local.com/?text=searchtext. Is there a way to achieve this? I at ...

Is there a way to create an infinite fade in/out effect for this?

Is there a way to ensure that the method runs after the "click" event in this code snippet? The code currently fades in and out the div #shape while the start variable is true, but when I call the "start" method from the "click" event, the browser stops wo ...

Button in the Web User Interface Control module doesn't trigger the click event

My C# code includes a function that dynamically creates buttons: private Button createPageButton(string id, string text, int navTo = 0) { Button btn = new Button(); btn.ID = id; btn.Text = text; btn.Click += new EventHandler(btnNavigate_To ...