我尝试在 .NET 4 下的 WebForms 应用程序中为仪表板构建通知。我已经下载了 SignalR 1.2 版(.net 客户端和服务器)并准备了一个简单的通知示例。不幸的是它不起作用,我不明白为什么。如果我输入 http://myserver.com/notificationSample/signalr/hubs出现 javascript 代理,看起来没问题。
看看下面的实现,有人看到任何错误吗?
a) 集线器实现
[HubName("NewMessage")]
public class NewMessageNotifier : Hub
{
public void NotifyDashboards()
{
Clients.All.NewMessageCreated();
}
}
b) 通知调用者(服务器)~/Pages/NotificationCaller.aspx
public partial class NotificationCaller : Page
{
private HubConnection connection;
private IHubProxy proxy;
protected void Page_Load(object sender, EventArgs e)
{
connection = new HubConnection( "http://myserver.com/notificationSample" );
proxy = connection.CreateHubProxy( "NewMessage" );
connection.Start().Wait();
}
// it is handler for onclick event on Button control
protected void NotifyDashboard(object sender, EventArgs e)
{
proxy.Invoke( "NotifyDashboards" ).Wait();
}
}
c) 仪表板(客户端,监听器)~/Pages/Dashboard.aspx
public partial class Dashboard: BasePage
{
private HubConnection connection;
protected void Page_Load(object sender, EventArgs e)
{
connection = new HubConnection( "http://myserver.com/notificationSample" );
var proxy = connection.CreateHubProxy("NewMessage");
proxy.On("NewMessageCreated", ShowNotification);
connection.Start();
}
private void ShowNotification()
{
ShowAlert("New message added!");
}
}
最佳答案
你用错了
首先 b和c都是客户端,服务端自己启动,你只需要添加
RouteTable.Routes.MapHubs();
到
Application_Start
global.asax 中的方法
第二
如果你打算使用网页作为客户端,你应该从javascript来做,因为你现在做的是行不通的,因为
connection.Start()
是异步的,请求将在它做任何事情之前结束,并且它不会等待传入的连接,因为所有连接都将被释放
现在怎么办?这里会占用很多页面,所以这里有几个链接
如果您错过了,a video that explains what is SignalR, how it works and a simple app你可以找到here
关于asp.net - SignalR 和 .NET 客户端在 ASP.NET WebForms 页面上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17661509/