我在发布这个问题时犹豫不决,因为网上有很多相同的答案但是我的运气不好,没有什么能帮助我。对于我的 Web 应用程序,我需要通知部分,为此我认为使用 SignalR 2。
但它不起作用。以下是完整的代码部分:
==>Hub Class
[HubName("MyHub")]
public class MyHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.displayStatus();
}
}
==>全局文件
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
SqlDependency.Start(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Application_End()
{
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
}
}
==>存储库
public class DAL
{
public List<DTO.Employee> GetEmployee()
{
List<DTO.Employee> l = new List<DTO.Employee>();
try
{
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
con.Open();
using (var cmd = new SqlCommand("select * from employee", con))
{
cmd.Notification = null;
SqlDependency dep = new SqlDependency(cmd);
dep.OnChange += new OnChangeEventHandler(Dep_OnChange);
using (var drd = cmd.ExecuteReader())
{
while (drd.Read())
{
l.Add(new DTO.Employee()
{
Id = Convert.ToInt64(drd["id"]),
Name = Convert.ToString(drd["name"])
});
}
}
}
}
}
catch { }
return l;
}
private void Dep_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
MyHub.Show();
}
}
}
==> Owin 创业班
[assembly: OwinStartupAttribute(typeof(SignalR2_App1.Startup))]
namespace SignalR2_App1
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
==> 查看
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="~/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var job = $.connection.MyHub;
job.client.displayStatus = function () {
getData();
}
$.connection.hub.start();
getData();
})
function getData() {
$.ajax({
url: "/data/getdata",
contentType: "application/json charset=utf-8",
dataType: "json",
type: "Post",
success: function (result) {
$.each(result, function (e, obj) {
$("#tbldata_tbody").append("<tr><td>" + obj.Id + "</td><td>" + obj.Name + "</td></tr>")
})
},
error: function () {
alert("Error");
}
})
}
</script>
<body>
<table id="tbldata">
<thead>
<tr>
<td>Id</td>
<td>Name</td>
</tr>
</thead>
<tbody id="tbldata_tbody"></tbody>
</table>
==>行动
[HttpPost]
public JsonResult GetData()
{
DAL.DAL O = new DAL.DAL();
return Json(O.GetEmployee());
}
您可以从以下链接下载整个代码:
代码链接