asp.net mvc4 signalR后台自推送

时间:2021-04-18 16:21:07

1.在引用中添加signalr后首选要引入Startup.cs类,在VS2012中添加Signalr后没有Startup.cs类然后就会报错 代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; using Owin;
using Microsoft.Owin;
[assembly: OwinStartup(typeof(CarportManage.Startup))]
namespace CarportManage
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
}

2写一个发送类

 using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace CarportManage.Models
{
public class seedmessage:Hub
{
public void Send(object message)
{
IHubContext chat = GlobalHost.ConnectionManager.GetHubContext<seedmessage>();
chat.Clients.All.add(message); }
}
}

3后台代码调用发送类

using CarportManage.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace CarportManage.Controllers
{
public class AlertController : Controller
{
//
// GET: /Alert/
CardManageEntities3 db = new CardManageEntities3();
public ActionResult Index()
{
return View();
}
public ActionResult show()
{
return View();
}
public ActionResult insert(FormCollection from)
{
int success;
try
{ CardManage t = new CardManage();
t.userName = from["add_name"];
t.userTel = from["add_tel"];
t.carNum = from["add_carNum"];
t.userDep = from["add_dep"];
t.fixedCarport = from["add_fixedCarport"];
db.CardManage.Add(t);
db.SaveChanges();
seedmessage s = new seedmessage(); s.Send(t);
success = ; }
catch (Exception)
{
success = ; }
//new { success = true }
return Content(success.ToString());
} }
}

4前端代码块

    Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery.signalR-2.1.2.js"></script>
<script src="~/Scripts/jquery.signalR-2.1.2.min.js"></script>
<script src="~/signalr/hubs"></script>
<script type="text/javascript">
var pushHub = $.connection.seedmessage; pushHub.client.add= function (message) { alert(message.userName);
alert(message.userTel);
}
$.connection.hub.start();
</script>
<title>接收端</title>
</head>
<body>
<div> </div>
</body>
</html>