You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Asp.net Core如何通过SignalR实现评论提交后全用户实时数据刷新

SignalR 实时评论功能完整实现方案

1. 后端基础配置

先确保SignalR服务已正确注册和配置:

  • Program.cs 注册服务与路由:
// 服务注册阶段添加
builder.Services.AddSignalR();

// 中间件配置阶段添加路由映射
app.MapHub<SignalServer>("/signalServer");
  • 新建SignalR Hub类:
using Microsoft.AspNetCore.SignalR;

public class SignalServer : Hub
{
}

2. 前端SignalR代码修正

替换你现有未完成的SignalR代码,新增连接异常重试逻辑,避免连接失败导致无推送:

/// <reference path="../lib/signalr/browser/signalr.js" />
$(() => {
    let connection = new signalR.HubConnectionBuilder()
        .withUrl("/signalServer")
        .build();

    // 连接失败自动重试
    async function startConnection() {
        try {
            await connection.start();
        } catch (err) {
            console.log("SignalR连接失败,3秒后重试", err);
            setTimeout(startConnection, 3000);
        }
    }

    // 连接断开自动重连
    connection.onclose(async () => {
        await startConnection();
    });

    // 启动连接
    startConnection();

    // 监听服务端推送的刷新事件
    connection.on("refreshData", function (subId) {
        // 只刷新当前页面对应主题的评论
        const currentSubId = @Model.Subject.Id;
        if (subId === currentSubId) {
            loadCommentData();
        }
    });

    // 加载评论方法
    function loadCommentData() {
        $.ajax({
            type: 'GET',
            url: '@Url.Action("refreshComments","Home")',
            data: { subId: @Model.Subject.Id },
            success: function (res) {
                $('#view-all').html(res);
            },
            error: function (err) {
                console.log("评论加载失败", err);
            }
        })
    }
});

3. 后端业务逻辑调整

你现有提交评论的代码只需修改推送逻辑,传入主题ID避免无关页面刷新:

var newComment = new CourseComment
{
    Comment = comment,
    Date = DateTime.Now,
    ApplicationUser = user,
    SubjectId = subId,
    CreatedDate = DateTime.Now
};
_courseCommnt.Entity.Insert(newComment);
await _courseCommnt.SaveAsync();

// 推送时带上主题ID
await _signalR.Clients.All.SendAsync("refreshData", subId);

_toastNotification.AddSuccessToastMessage("تم ارسال التعليق بنجاح");

var courseComments = await _courseCommnt.Entity.GetAll().Include(a => a.ApplicationUser)
    .Where(a => a.SubjectId == subId).OrderByDescending(a => a.Date).AsNoTracking().ToListAsync();

var vm = new HomeViewModel
{
    CourseComments = courseComments
};

return Json(new
{
    isValid = true,
    html = Helper.RenderRazorViewToString(this, "_SubjectComments", vm)
});

4. 新增评论刷新接口

新增refreshComments接口供前端拉取最新评论:

public async Task<IActionResult> refreshComments(int subId)
{
    var courseComments = await _courseCommnt.Entity.GetAll()
        .Include(a => a.ApplicationUser)
        .Where(a => a.SubjectId == subId)
        .OrderByDescending(a => a.Date)
        .AsNoTracking()
        .ToListAsync();
    var vm = new HomeViewModel
    {
        CourseComments = courseComments
    };
    return PartialView("_SubjectComments", vm);
}

内容的提问来源于stack exchange,提问作者Mohaned Ghawar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 09:45:08