【问题标题】:SignalR notification implementation with Angular and C# for specific client使用 Angular 和 C# 为特定客户端实现 SignalR 通知
【发布时间】:2019-09-23 05:28:06
【问题描述】:

我正在尝试使用 C# 和 Angular 8 为特定客户端实现 SignalR 通知中心。

我已经成功地使用用户名验证为特定客户端制作了广播通知实现,该用户名验证还向所有客户端广播并在角度端代码验证用户名。

很难为特定客户端完成这项工作,可能是通过注册连接 ID/用户名,将消息发送到特定客户端或基于角色的客户端。

我正在共享我尝试过使用用户名的代码,但需要一些其他方式的调整(可能是通过注册连接 ID/用户名)。请需要您的支持。

我已经检查了所有 stackoverflow 上的其他帖子,但没有提供相同的具体答案。

package.json:

{
  "name": "angular-client",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~7.2.0",
    "@angular/common": "~7.2.0",
    "@angular/compiler": "~7.2.0",
    "@angular/core": "~7.2.0",
    "@angular/forms": "~7.2.0",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/router": "~7.2.0",
    "@aspnet/signalr": "^1.1.4",
    "core-js": "^2.5.4",
    "font-awesome": "^4.7.0",
    "primeicons": "^1.0.0",
    "primeng": "^8.0.0-rc.1",
    "rxjs": "~6.3.3",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.13.0",
    "@angular/cli": "~7.3.8",
    "@angular/compiler-cli": "~7.2.0",
    "@angular/language-service": "~7.2.0",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.2.2"
  }
}

Angular - app.component.ts

import { Component, OnInit } from '@angular/core';
import { MessageService } from 'primeng/api';

import * as signalR from '@aspnet/signalr';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [MessageService]
})
export class AppComponent implements OnInit {

  constructor(private messageService: MessageService) { }

  ngOnInit(): void {
    const connection = new signalR.HubConnectionBuilder()
      .configureLogging(signalR.LogLevel.Information)
      .withUrl("http://localhost:5627/notify")
      .build();

    connection.start().then(function () {
      console.log('Connected!');
    }).catch(function (err) {
      return console.error(err.toString());
    });

    connection.on("BroadcastMessage", (type: string, payload: string, username: string) => {
      console.log("username:"+username);
      if(username == 'myuser') {
        this.messageService.add({ severity: type, summary: payload, detail: 'Via Apointment - '+username });
      }
    });
  }
}

C# - MessageController.ts:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using SignalRHub;
using System;

namespace SignalR_Hub.Controllers
{
    [Route("api/message")]
    [ApiController]
    public class MessageController : ControllerBase
    {
        private IHubContext<NotifyHub, ITypedHubClient> _hubContext;

        public MessageController(IHubContext<NotifyHub, ITypedHubClient> hubContext)
        {
            _hubContext = hubContext;
        }

        [HttpPost]
        public string Post([FromBody]Message msg)
        {
            string retMessage;



            try
            {
                // For Broadcasting
                //_hubContext.Clients.All.BroadcastMessage(msg.Type, msg.Payload);
                //retMessage = "Success";

                // For Specific Client
                _hubContext.Clients.All.BroadcastMessage(msg.Type, msg.Payload, msg.Username);
                retMessage = "Success";
            }
            catch (Exception e)
            {
                retMessage = e.ToString();
            }

            return retMessage;
        }
    }
}

使用 RestFul 服务请求:

{
 "Type": "info",
 "Payload": "One new Client is waiting for you.",
 "username": "myuser"
}

如果您需要任何信息,请告诉我。

【问题讨论】:

    标签: c# .net angular signalr


    【解决方案1】:

    我相信这个问题在这里得到了回答:

    signalr-sending-a-message-to-a-specific-user

    您可以使用连接 ID 并将其映射到连接 ID 和用户之间。

    【讨论】:

    • 这对我没有帮助,因为它主要讨论 C# .net 方面的代码。我也需要有角度的侧面实现。
    • 你可以看到这个带有聊天的 git 项目,因为聊天是针对特定于客户端的消息或特定于组的消息完成的,它可以帮助你。 github.com/nrcpp/angular-asp.net-mvc-chat
    • 我检查了 github 链接。它说的是聊天,但是一旦我在本地环境中对其进行了配置,它就会显示“向所有人发送消息”,这又是一种广播。直到现在试图破解它,但还没有运气。
    • 到目前为止有什么解决办法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 2016-05-27
    • 1970-01-01
    相关资源
    最近更新 更多