从Windows服务访问Web App中的SignalR Hub

时间:2016-06-22 21:15:55

标签: javascript c# asp.net signalr

我已经创建了一个SignalR中心并让它在我的网络应用程序中运行。现在,我正在尝试使用单独的Windows服务向该中心发送消息。根据我用于集线器连接URL的内容,我得到401 Unauthorized或SocketException。为了让Windows服务能够向集线器发送消息,我缺少什么?

网络应用中的启动课:

[assembly: OwinStartup(typeof(MmaWebClient.Startup))]
namespace MmaWebClient
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

网络应用中的Hub类:

[HubName("scannerHub")]
public class ScannerHub : Hub
{
    public void Send(string message)
    {
        Clients.All.broadcastMessage(message);
    }
}

index.html中的脚本引用:

<script src="../scripts/jquery-1.9.1.js"></script>
<script src="../scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="../signalr/hubs"></script>

我的AngularJS控制器中的JavaScript(可行):

    if (!$scope.state.hub) {
        $scope.state.hub = $.connection.scannerHub;
        $scope.state.hub.client.broadcastMessage = function (message) {
            onSubIdOrCassetteIdEntered(scanText);
        }
        $.connection.hub.start()
            .done(function () {
                console.log('Connected to SignalR. Connection ID: ' + $.connection.scannerHub.connection.id +
                    '. URL: ' + $.connection.scannerHub.connection.baseUrl +$.connection.scannerHub.connection.appRelativeUrl);
            })
            .fail(function (response) {
                showInfoModal.show('Connection to SignalR Failed', 'This connection is necessary to read the ' +
                    'scans from the scanner. Response message: ' + response.message);
            });
    }

最后,在Windows服务中:

    static void Main(string[] args)
    {
        AutoResetEvent scanReceivedEvent = new AutoResetEvent(false);

        var connection = new HubConnection("http://localhost/MmaWebClient/signalr");
        //Make proxy to hub based on hub name on server
        var myHub = connection.CreateHubProxy("scannerHub");
        //Start connection

        connection.Start().ContinueWith(task => {
            if (task.IsFaulted) {
                Console.WriteLine("There was an error opening the connection:{0}",
                                  task.Exception.GetBaseException());
            } else {
                Console.WriteLine("Connected");
            }

        }).Wait();


        myHub.On<string>("broadcastMessage", param => {
            Console.WriteLine("Scan received from server = [{0}]", param);
            scanReceivedEvent.Set();
        });

        string input = "";

        do
        {
            Console.WriteLine("Enter a value to send to hub or Q to quit.");

            input = Console.ReadLine();

            if (input.ToUpperInvariant() != "Q")
            {
                myHub.Invoke<string>("Send", input);
                scanReceivedEvent.WaitOne(1000);
            }

        } while (input.ToUpperInvariant() != "Q");

        connection.Stop();
    }

当我在上面的代码中创建新的集线器连接时,我已经尝试了这三个URL但没有成功:

var connection = new HubConnection("http://localhost/MmaWebClient/signalr");
var connection = new HubConnection("http://localhost:8080");
var connection = new HubConnection("http://localhost");

第一个网址:401未经授权
第二个URL:套接字异常
第三个网址:404 Not Found

2 个答案:

答案 0 :(得分:2)

我能够通过在连接上设置凭据(下面的第二行)来使其工作:

var connection = new HubConnection("http://localhost/MmaWebClient");
connection.Credentials = CredentialCache.DefaultNetworkCredentials;
var myHub = connection.CreateHubProxy("scannerHub");

答案 1 :(得分:0)

不是一个明确的答案,但这是映射SignalR端点的另一种方法。很难弄错这个URL。

ASP.NET Startup.cs

public void Configuration(IAppBuilder app)
{    
    app.Map("/foo", map =>
    {
        //Specify according to your needs
        var hubConfiguration = new HubConfiguration
        {
           EnableDetailedErrors = true
        };
        map.RunSignalR(hubConfiguration);
    });

    ConfigureAuth(app);
}

客户端

var hubConnection = new HubConnection("http://localhost/foo", useDefaultUrl: false);
var proxy = hubConnection.CreateHubProxy("scannerHub");