asp.net - SignalR 和 .NET 客户端在 ASP.NET WebForms 页面上不起作用

标签 asp.net webforms signalr

我尝试在 .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 Simple Tutorial

The Hubs Server API

The Hubs JavaScript API

如果您错过了,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/

相关文章:

asp.net - 回发间歇性不适用于 ASP.NET 3.5 和 IE?

javascript - 如何将 SignalR 包含在 gulp 构建过程中?

ASP.NET MVC 正在用重复的内容破坏我的页面

ASP.NET 动态命令按钮事件未触发

javascript - 使用 jQuery 在 gridview 中查找选中行的值

javascript - 初始加载和更新之间的 SignalR

Azure、SignalR 和 Web Api 不向客户端发送消息

javascript - jQuery 数据表自定义排序和过滤

javascript - 服务器端的 AngularJS 变量

authentication - 如何在 AspNetCore SignalR Alpha 中启用 Windows 身份验证