【问题标题】:How to connect signalR from angularJs如何从angularJs连接signalR
【发布时间】:2017-02-01 00:50:02
【问题描述】:

我在 .NET 中将 Web 应用程序开发为两个独立的应用程序,后端使用 webapi c#,用户界面使用 AngularJS。我只想在这个项目中添加聊天选项。我已经安装了 SignalR 并在 webapi 中添加了 ChatHub.cs 类。

enter image description here

在 WebAPI 中有一个名为 Startup.cs 的类

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();
        config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;
        WebApiConfig.Register(config);
        app.UseCors(CorsOptions.AllowAll);
        ConfigureAuth(app);
        app.UseWebApi(config);

        app.MapSignalR();//added after installation of SignalR package
    }
}

ChatHub 类

public class ChatHub : Hub
{
   public static string emailIDLoaded = "";
    public void Connect(string userName, string email)
    {
        emailIDLoaded = email;
        var id = Context.ConnectionId;
        using (SmartCampEntities dc = new SmartCampEntities())
        {

                var userdetails = new ChatUserDetail
                {
                    ConnectionId = id,
                    UserName = userName,
                    EmailID = email
                };
                dc.ChatUserDetails.Add(userdetails);
                dc.SaveChanges();

               }
            }

        }

无论我从用户界面发送什么请求,它都会到达 webAPI 中的相应控制器。例如

 $http({
    method: 'GET',
    url: $scope.appPath + "DashboardNew/staffSummary"  //[RoutePrefix]/[Route]
}).success(function (result, status) {
    data = result;
});

我的用户界面是一个单独的应用程序。如何从 UI 连接 signalR。 我尝试了一些东西,但没有成功。谁能建议我如何让它工作

html代码

<div>    
<a class="btn btn-blue"  ng-click="sendTask()">SendTask</a>

javascript

angular.module('WebUI').controller('DashboardCtrl', function ($scope, $window, $http, $modal, ngTableParams) {
$scope.header = "Chat";

 $scope.sendTask = function () {
    $http({
        method: 'POST',
        url: $scope.appPath + hubConnetion.server.sendTask("userName","email"),
    })   
}

});

【问题讨论】:

  • 这与从网页定期使用 SignalR 没有什么不同。该文档很好,并且有很多关于如何使用它的示例。
  • 你能分享任何例子或链接吗
  • 不清楚您真正需要什么,或者更好的是,您需要帮助解决哪些故障。您想知道如何在 Angular 中集成 Signalr 启动,或者您遇到了失败,例如 CORS?
  • 我想知道如何将 SignalR 集成到现有项目中。因为 Startup.cs 已经存在,所以我不知道我应该做哪些改变

标签: javascript c# asp.net angularjs asp.net-web-api


【解决方案1】:

基础知识:

您可以连接到您的信号器服务器,您必须将客户端代码包含到您的页面中。之前包含 jquery 也很重要。 至少您还可以在使用集线器的情况下包含生成集线器文件:

<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/jquery.signalR-2.1.0.min.js"></script>
<script src="signalr/hubs"></script>

基本示例:

这里有一个完整的示例(没有和有生成的集线器代理):

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />       
</head>
<body>
    <div class="container">
        <div class="row">
            <!-- Title -->
            <h1>SignalR Sample</h1>
        </div>
        <div class="row">
            <!-- Input /Button-->
            <input type="text" id="inputMsg" />
            <button button="btn btn-default" id="btnSend">Send</button>
        </div>
        <div class="row">
            <!-- Message list-->
            <ul id="msgList"></ul>
        </div>
    </div>
    <script src="Scripts/jquery-1.6.4.js"></script>
    <script src="Scripts/jquery.signalR-2.2.0.js"></script>
    <script src="http://[LOCATIONOF YOUR HUB]/signalr/hubs"></script>
    <script>
        // ------------------- Generated Proxy ----------------------------
        $(function () {
            $.connection.hub.url = "[LOCATION WHERE YOUR SERVICE IS RUNNING]/signalr";
            var chat = $.connection.myChat;

            chat.client.addMessage = function (name, message) {
                $('#msgList').append('<li><strong>' + name
                   + '</strong>:&nbsp;&nbsp;' + message + '</li>');
            };
            $.connection.hub.start({}).done(function () {
                $('#btnSend').click(function () {
                    chat.server.Send("Stephan", $('#inputMsg').val());
                    $('#inputMsg').val('').focus();
                });
            })
        });
        //// ------------------- Without Proxy ----------------------------
        //$(function () {
        //    var connection = $.hubConnection("http://localhost:8080/signalr");
        //    var chatHubProxy = connection.createHubProxy('chatHub');
        //    chatHubProxy.on('AddMessage', function (name, message) {
        //        console.log(name + ' ' + message);
        //        $('#msgList').append('<li><strong>' + name
        //      + '</strong>:&nbsp;&nbsp;' + message + '</li>');

        //    });
        //    connection.start().done(function () {
        //        $('#btnSend').click(function () {
        //            chatHubProxy.invoke('send', "Stephan", $('#inputMsg').val());
        //            $('#inputMsg').val('').focus();
        //        });
        //    });
        //});

    </script>
</body>
</html>

更多详情见: http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client

SignalR Angular 模块:

还有一个“帮助模块”,您可以在 angularjs 中使用它来处理信号器: https://github.com/JustMaier/angular-signalr-hub

【讨论】:

    【解决方案2】:

    我可以通过将以下代码添加到我的 Startup.Auth.cs 来连接 webapi

    public void ConfigureAuth(IAppBuilder app)
        {
            app.UseOAuthBearerTokens(OAuthOptions);
    
            //by adding below code 
            app.UseCors(CorsOptions.AllowAll);
            app.MapSignalR(new HubConfiguration { EnableJSONP = true });
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-04
      • 1970-01-01
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多