Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用信号器从实时SQL更新数据时出现问题_C#_Asp.net Core 2.0_Signalr Hub_Asp.net Core Signalr - Fatal编程技术网

C# 使用信号器从实时SQL更新数据时出现问题

C# 使用信号器从实时SQL更新数据时出现问题,c#,asp.net-core-2.0,signalr-hub,asp.net-core-signalr,C#,Asp.net Core 2.0,Signalr Hub,Asp.net Core Signalr,我使用SignalR实时更新记录,并将它们显示在一个表中,以便客户端连接到SQL,我建立连接,当我运行应用程序时,它们加载所有数据,但当我更新数据库时,更新不会显示在客户端表中,但当我在浏览器中给出F5(刷新)时,当前数据刚刚显示出来。我找不到错误,也没有看到任何控制台错误。我附上了建议代码:)谢谢 客户: <body> <h1>Hola</h1> <div class="table table-responsive"> <tabl

我使用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>
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?}");
        });
    }
}

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

$.ajax({  cache: false,  ...});
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);
    }
}
public class TablaHub : Hub
{
}
$.ajax({  cache: false,  ...});