English 中文(简体)
如何确保在聊天时向接收方立即展示信息
原标题:How to ensure that messages in chat app are displayed immediately to the recipient

我正在利用伙伴关系建立一个一对一的聊天申请。 NET Core MVC, identity, and signR. 然而,我遇到一个问题,即在从清单中挑选用户并发送信息之后,电文立即出现。 由于我已在数据库中保存了浏览器,因此在更新浏览器后才会发现。 这是我的控制者。

public class MessagingController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly UserManager<AppDbContext> _userManager;
        private readonly IHubContext<MessageHub> _hubContext;

        public MessagingController(ApplicationDbContext context, UserManager<AppDbContext> userManager, IHubContext<MessageHub> hubContext)
        {
            _context = context;
            _userManager = userManager;
            _hubContext = hubContext;
        }

        public IActionResult Index()
        {
            var currentUserId = _userManager.GetUserId(User);
            var users = _userManager.Users.Where(u => u.Id != currentUserId).ToList();
            var messages = _context.Messages
                .Where(m => m.SenderId == currentUserId || m.ReceiverId == currentUserId)
                .Include(m => m.Sender)
                .Include(m => m.Receiver)
                .OrderByDescending(m => m.Timestamp)
                .ToList();
            var viewModel = new IndexViewModel
            {
                Users = users,
                Messages = messages,
                CurrentUserId = currentUserId  // Add this line to pass the current user ID to the view
            };

            return View(viewModel);
        }



      
        [HttpPost]
        public async Task<IActionResult> SendMessage(string receiverId, string content)
        {
            var senderId = _userManager.GetUserId(User);
            var senderName = _userManager.GetUserName(User);

            var message = new Message
            {
                SenderId = senderId,
                ReceiverId = receiverId,
                Content = content,
                Timestamp = DateTime.Now
            };

            _context.Messages.Add(message);
            await _context.SaveChangesAsync();

            // Send the message to the sender and the selected user using SignalR
            await _hubContext.Clients.User(senderId).SendAsync("ReceiveMessage", new { senderName, content, receiverId });
            await _hubContext.Clients.User(receiverId).SendAsync("ReceiveMessage", new { senderName, content, receiverId });

            return RedirectToAction(nameof(Index));
        }


        public IActionResult LoadMessages(string receiverId)
        {
            var currentUserId = _userManager.GetUserId(User);
            var messages = _context.Messages
                .Where(m => (m.SenderId == currentUserId && m.ReceiverId == receiverId) ||
                            (m.SenderId == receiverId && m.ReceiverId == currentUserId))
                .Include(m => m.Sender)
                .Include(m => m.Receiver)
                .OrderBy(m => m.Timestamp)
                .ToList();

            //return PartialView("_MessageListPartial", messages);
            return PartialView("_ChatPartial", messages);
        } 

以及我的看法

@using System.Security.Claims

<!-- Index.cshtml -->
@model IndexViewModel

<div style="display: flex;">

    <!-- Left column: List of Users -->
    <div style="flex: 1; padding-right: 20px;">
        <h1>Users</h1>
        <form asp-action="SendMessage" asp-controller="Messaging" method="post">
            <label>Select a User:</label>

            @foreach (var user in Model.Users)
            {
                <label>
                    <input type="radio" name="receiverId" value="@user.Id" />
                    @user.UserName
                </label>
                <br />
            }

            <label>Message:</label>
            <input type="text" name="content" />
            <button type="submit">Send Message</button>
        </form>
    </div>
    <!-- Right column: Messages -->
    <div style="flex: 2;">
        <h1>Messages</h1>
        <ul id="messagesList">
            @if (Model.Messages.Any())
            {
                @foreach (var message in Model.Messages)
                {
                    <li>
                        @if (message.Sender != null)
                        {
                            <strong>@message.Sender.UserName:</strong>
                        }
                        else
                        {
                            <strong>Unknown User:</strong>
                        }
                        @message.Content
                    </li>
                }
            }
            else
            {
                <p>No messages available.</p>
            }
        </ul>
    </div>


</div>
<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script>
    const connection = new signalR.HubConnectionBuilder()
        .withUrl("/messageHub")
        .build();

    connection.start().then(function () {
        console.log("SignalR connection established.");
    }).catch(function (err) {
        return console.error(err.toString());
    });

    connection.on("ReceiveMessage", function (message) {
        // Handle received message, e.g., update the UI
        console.log("Received message:", message);

        // Get the current user s ID
        const currentUserId = "@User.FindFirst(ClaimTypes.NameIdentifier)?.Value";

        // Get the selected receiver s ID from the radio buttons
        const receiverId = document.querySelector( input[name="receiverId"]:checked ).value;

        // Check if the message is from the sender and to the selected user
        if (message.senderId === currentUserId && message.receiverId === receiverId) {
            // Append the sent message to the messages list
            const messagesList = document.getElementById("messagesList");
            const listItem = document.createElement("li");
            listItem.innerHTML = `<strong>You:</strong> ${message.content}`;
            messagesList.appendChild(listItem);
        }

        // Check if the message is from the receiver and from the selected user
        if (message.receiverId === currentUserId && message.senderId === receiverId) {
            // Append the received message to the messages list
            const messagesList = document.getElementById("messagesList");
            const listItem = document.createElement("li");
            listItem.innerHTML = `<strong>${message.senderName}:</strong> ${message.content}`;
            messagesList.appendChild(listItem);
        }
    });
</script>
问题回答

在四舍五入之后,我看到康索尔窗口的电文活化。

在重新检查你的法典后,我发现这一法典应当成为根本原因。

const currentUserId = "@User.FindFirst(ClaimTypes.NameIdentifier)?.Value";

在《拉汉斯宣言》生效之后,这一《宣言》应首先生效,成为《公约》的《公约》的《公约》和《公约》的《公约》文本。 最初的用户是这样,修改后的代码如下。

enter image description here

@model YourNamespace.IndexViewModel

<div style="display: flex;">
    <!-- Left column: List of Users -->
    <div style="flex: 1; padding-right: 20px;">
        <h1>Users</h1>
        <form asp-action="SendMessage" asp-controller="Messaging" method="post">
            <label>Select a User:</label>
            @foreach (var user in Model.Users)
            {
                <label>
                    <input type="radio" name="receiverId" value="@user.Id" />
                    @user.UserName
                </label>
                <br />
            }

            <label>Message:</label>
            <input type="text" name="content" />
            <button type="submit">Send Message</button>
        </form>
    </div>
    
    <!-- Right column: Messages -->
    <div style="flex: 2;">
        <h1>Messages</h1>
        <ul id="messagesList">
            @if (Model.Messages.Any())
            {
                @foreach (var message in Model.Messages)
                {
                    <li>
                        @if (message.Sender != null)
                        {
                            <strong>@message.Sender.UserName:</strong>
                        }
                        else
                        {
                            <strong>Unknown User:</strong>
                        }
                        @message.Content
                    </li>
                }
            }
            else
            {
                <p>No messages available.</p>
            }
        </ul>
    </div>
</div>

<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script>
    // Global variable for the current user s ID
    const currentUserId = "@User.FindFirst(ClaimTypes.NameIdentifier)?.Value";

    const connection = new signalR.HubConnectionBuilder()
        .withUrl("/messageHub")
        .build();

    connection.start().then(function () {
        console.log("SignalR connection established.");
    }).catch(function (err) {
        return console.error(err.toString());
    });

    connection.on("ReceiveMessage", function (message) {
        console.log("Received message:", message);

        // Append the message to the messages list
        const messagesList = document.getElementById("messagesList");
        const listItem = document.createElement("li");

        if (message.senderId === currentUserId) {
            listItem.innerHTML = `<strong>You:</strong> ${message.content}`;
        } else {
            listItem.innerHTML = `<strong>${message.senderName}:</strong> ${message.content}`;
        }

        messagesList.appendChild(listItem);
    });
</script>




相关问题
ASP.NET Core MVC Register/Login Pages not working

I am following Tim Corey s video on "ASP.NET Core MVC" and I ve created a test project with a register/login authentication system using Identity (in .NET 6.0). My issue is that the Register ...

Upload in the database and download it in ASP.NET Core V5

I want the file that I uploaded in the documentUploadProvinceLevels database table to be able to be download.I implemented the file upload part, but I don t know what to do for downloading. please ...

Set selected value to @html.dropdownlistfor control

My View code: Unit @Html.DropDownListFor(m => m.Unit, UnitList, new { @class = "form-select" }) Gatepass Category @Html.DropDownListFor(m => m.GatePassCategory, GatepassCategoryList, ...

热门标签