使用SignalR从实时SQL更新数据的问题

问题描述 投票:0回答:1

我正在使用SignalR实时更新记录,并在与SQL连接的客户端表中显示它们,我建立了连接,当我运行应用程序时,它们会加载所有数据,但是当我更新数据库时,更新不会在客户端表中显示,但是当我在浏览器中输入F5(刷新)时,只会显示当前数据。我找不到错误,也没有看到任何控制台错误。我附上了代码以获取建议:)谢谢

客户:

<body>
<h1>Hola</h1>

<div class="table table-responsive">
    <table id="tbl-productos" class="table table-bordered table-striped"></table>
</div>

<script src="~/jquery/jquery.min.js"></script>
<script src="~/aspnet/signalr/dist/browser/signalr.min.js"></script>

<script>
    $(function () {
        fnCrearTabla();
    });

    function fnCrearTabla() {
        var tabla = $("#tbl-productos");
        $.ajax({
            url: "/Home/listadoProductos",
            type: "GET",
            contentType: "application/json; charset-utf-8",
            dataType: "json",
            success: function (data) {
                if (data.length > 0) {
                    //tabla.empty();
                    var thead = "<tr>";
                    thead += "<th>id</th>"
                    thead += "<th>nombre</th>"
                    thead += "<th>precio</th>"
                    thead += "<th>Stock</th>"
                    thead += "</tr>"

                    tabla.append(thead);

                    var array = [];
                    var tbody = "";

                    for (var i = 0; i < data.length; i++) {
                        tbody += "<tr>";
                        tbody += "<td>" + data[i].id + "</td>"
                        tbody += "<td>" + data[i].nombre + "</td>"
                        tbody += "<td>" + data[i].precio + "</td>"
                        tbody += "<td>" + data[i].stock + "</td>"
                        tbody += "</tr>"
                    }

                    array.push(tbody);
                    tabla.append(array.join(""));
                }
            },
            error: function (e) {
                console.error(e);
            }
        });

    }

    var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:63257/tablaHub").build();
    //connection.serverTimeoutInMilliseconds = 100000; // 100 second}

    connection.on("ActualizarGrilla", function () {
        fnCrearTabla();
    });

    connection.start().catch(function () {
         console.error(e);
    });
</script>

控制器:

public class HomeController : Controller
{
    private readonly IProductoServicio _productoServicio;

    public HomeController(IProductoServicio productoServicio)
    {
        this._productoServicio = productoServicio;
    }

    public IActionResult Index()
    {
        return View();
    }

    public JsonResult listadoProductos()
    {
        var data = _productoServicio.Listado().ToList();
        return Json(data);
    }
}

Startup.cs

public class Startup
{
    private readonly IWebHostEnvironment _webHostEnvironment;
    private readonly IConfiguration _configuration;

    public Startup(IWebHostEnvironment webHostEnvironment)
    {
        this._webHostEnvironment = webHostEnvironment;

        var builder = new ConfigurationBuilder()
            .SetBasePath(_webHostEnvironment.ContentRootPath)
            .AddJsonFile("appsettings.json")
            .AddEnvironmentVariables();
        _configuration = builder.Build();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(_configuration);

        #region IOC

        services.AddScoped<IProductoRepositorio, ProductoRepositorio>();
        services.AddScoped<IProductoServicio, ProductoServicio>();

        #endregion

        services.AddSignalR();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseDeveloperExceptionPage();
        app.UseStaticFiles();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<TablaHub>("/tablaHub");
            endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

这就是一切发生的地方,实现的类--->

ProdcutoRepositorio.cs:

public class ProductoRepositorio : IProductoRepositorio
{
    private readonly IConfiguration _configuration;
    private readonly IHubContext<TablaHub> _tablaHub;

    public ProductoRepositorio(IConfiguration configuration,
                               IHubContext<TablaHub> tablaHub)
    {
        this._configuration = configuration;
        this._tablaHub = tablaHub;
    }

    public IEnumerable<Producto> Get()
    {
        List<Producto> listProducto = null;
        Producto oProducto = null;
        SqlDependency dependency = null;

        var connectionString = _configuration.GetConnectionString("dbconnection");

        using (SqlConnection cn = new SqlConnection(connectionString))
        {
            try
            {
                cn.Open();
                SqlCommand cmd = new SqlCommand("upsGetProductos", cn);
                cmd.CommandType = CommandType.StoredProcedure;

                #region SqlDependecy

                cmd.Notification = null;
                dependency = new SqlDependency(cmd);
                dependency.OnChange += DetectarCambios;
                SqlDependency.Start(connectionString);

                #endregion

                SqlDataReader dr = cmd.ExecuteReader();

                if (dr.HasRows)
                {
                    listProducto = new List<Producto>();

                    while (dr.Read())
                    {
                        oProducto = new Producto()
                        {
                            Id = dr.IsDBNull(dr.GetOrdinal("Id")) ? -1 : dr.GetInt32(dr.GetOrdinal("Id")),
                            Nombre = dr.IsDBNull(dr.GetOrdinal("Nombre")) ? "nodata" : dr.GetString(dr.GetOrdinal("Nombre")),
                            Precio = dr.IsDBNull(dr.GetOrdinal("Precio")) ? Convert.ToDecimal(0) : dr.GetDecimal(dr.GetOrdinal("Precio")),
                            Stock = dr.IsDBNull(dr.GetOrdinal("Stock")) ? -1 : dr.GetInt32(dr.GetOrdinal("Stock"))
                        };
                        listProducto.Add(oProducto);
                    }
                }
                return listProducto;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }

    public void DetectarCambios(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            _tablaHub.Clients.All.SendAsync("ActualizarGrilla");
        }

        Get();
    }

    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }
}

还有我的中心课程... TablaHub:

public class TablaHub : Hub
{
}
c# asp.net-core-2.0 signalr-hub asp.net-core-signalr
1个回答
0
投票

我认为您可能正在面临缓存问题,因为您正在进行ajax调用。您可以先查看浏览器中的网络流量,以查看更改后是否真正在调用后端以获取数据。如果您在fnCrearTabla内添加一些控制台日志来检查您是否正在接收来自signalR的消息,这对于调试很有用。以下代码将禁用缓存

© www.soinside.com 2019 - 2024. All rights reserved.