【问题标题】:How to read data sent from web api using signalr in angular?如何使用信号器以角度读取从 Web api 发送的数据?
【发布时间】:2019-11-26 23:36:22
【问题描述】:

我想通过angular客户端中的signalr读取从asp.net web api发送的数据。

为此,我在下面给出的 Web api 中创建了 Hub:

//ProgressHub.cs
public class ProgressHub : Hub
{
    public Task Send(string data)
    {
        return Clients.All.SendAsync("Send", data);
    }
    public async Task<string> GetServerTime(IProgress<int> prog)
    {
        await Task.Run(() => {
            for (int i = 0; i < 10; i++)
            {
                prog.Report(i * 10);
                // Call to your client side method.
                Clients.Client(Context.ConnectionId).progress(i);
                System.Threading.Thread.Sleep(200);
            }
        });

        return DateTime.Now.ToString()+" Test";
    }
}

//startup.cs
app.MapSignalR();

在 Angular 客户端中,

    private proxy: any;
    private proxyName: string = 'progressHub';
    private connection: any;
    constructor(){

    // create hub connection  
    this.connection = $.hubConnection("http://localhost:53642/");
    // create new proxy as name already given in top  
    this.proxy = this.connection.createHubProxy(this.proxyName);
    // call the connecion start method to start the connection to send and receive events.  
    this.startConnection();
    this.proxy.on('Send', (data: any) => {
      const received = `Received: ${data}`;
      alert(received);   //here i want to get the data
    });

  }
  startConnection(): void {
    this.connection.start().done((data: any) => {
      console.log('Now connected ' + data.transport.name + ', connection ID= ' + data.id);
      this.proxy.invoke('GetServerTime', serverMessage => 
      {
           console.log(serverMessage) 
      });
    }).fail((error: any) => {
      console.log('Could not connect ' + error);
    });
  }

当我运行调试应用程序时,客户端成功连接到信号器 控制台输出:

Now connected webSockets, connection ID= 19156d89-d82c-46f9-a109-d8a4828f8ea9

但不返回任何我想提醒的数据。

【问题讨论】:

    标签: c# angular asp.net-core asp.net-core-mvc signalr


    【解决方案1】:

    编辑:仅适用于 asp.net 核心

    使用 @aspnet/signalr 包与 SignalR 配合使用

    示例 私人枢纽;

    this.hub = new HubConnectionBuilder()
      .withUrl("/signalr")
      .configureLogging(LogLevel.Error)
      .build();
    
    this.hub.start().catch(err => console.error(err.toString()));
    

    然后监听服务器发送的事件

    this.hub.on("Send", (data) =>
      console.log(data);
    );
    

    更新

    public class HomeController : Controller
    {
        private readonly IHubContext<NotificationHub> _hubContext;
    
        public HomeController(IHubContext<NotificationHub> hubContext)
        {
            _hubContext = hubContext;
        }
    }
    
    public async Task<IActionResult> Index()
    {
        await _hubContext.Clients.All.SendAsync("Notify", $"Home page loaded at: {DateTime.Now}");
        return View();
    }
    

    您可以查看here

    【讨论】:

    • 感谢您的回复....但是我正在使用 asp.net web api...所以我必须在 angular 客户端中使用“signalr”包...参考这个... docs.microsoft.com/en-us/aspnet/core/signalr/…
    • 我尝试了你的答案..但在“this.hub.start()”处给了我错误......错误:检测到与 ASP.NET SignalR 服务器的连接尝试。此客户端仅支持连接到 ASP.NET Core SignalR 服务器
    • 抱歉再次检查我的答案。你需要在这个包中使用 ASP.Net Core
    • 你对asp.net web api有什么想法吗.....?我应该如何通过 signalr 从 api 获取数据?
    【解决方案2】:

    我得到了答案:

    我的新中心(在 asp.net web api 上)如下所示:

    public class ProgressHub : Hub
        {
            public string msg = string.Empty;
            public int count = 0;
    
            public void CallLongOperation()
            {
                Clients.Caller.sendMessage(msg, count);
            }
        }
    

    在 Angular 客户端中(使用信号器):

    constructor() {
        // create hub connection  
        this.connection = $.hubConnection("http://localhost:53642/");
    
        // create new proxy as name already given in top  
        this.proxy = this.connection.createHubProxy(this.proxyName);
    
        // call the connecion start method to start the connection to send and receive events. 
        this.proxy.on('sendMessage', (percentage) => 
        {
          this.onProgressReceived(percentage)
        });
        this.startConnection();
      }
    
      startConnection(): void {
        this.connection.start().done((data: any) => {
          this.getProgress();
        }).fail((error: any) => {
          console.log('Could not connect ' + error);
        });
      }
      private getProgress(): void {
        this.proxy.invoke('CallLongOperation')
          .catch((error: any) => {
            console.log('broadcastMessage error -> ' + error);
          });
      }
    
      private onProgressReceived(percentage: number) {
       //your code logic with data
      }
    

    【讨论】:

      【解决方案3】:

      Github

      • 带有 netcoreapp2.2

        的 Web API

        安装Microsoft.AspNetCore.SignalR

      现在像下面的例子一样发送 signalR 消息

      [Route("api/[controller]")]
          [ApiController]
          [EnableCors("CorsPolicy")]
          public class ValuesController : ControllerBase
          {
              private IHubContext<SignalRHub> _hub;
              public ValuesController(IHubContext<SignalRHub> hub)
              {
                  _hub = hub;
              }
      
              // GET api/values
              [HttpGet]
              public ActionResult<IEnumerable<string>> Get()
              {
                  _hub.Clients.All.SendAsync("clientMethodName", "get all called");
                  return new string[] { "value1", "value2" };
              }
      
              // GET api/values/5
              [HttpGet("{connectionId}")]
              public ActionResult<string> Get(string connectionId)
              {
                  _hub.Clients.Client(connectionId).SendAsync("clientMethodName", "get called");
                  return "value";
              }
          }
      }
      

      Startup.cs

      客户端在端口 4200 ("http://localhost:4200") 上运行。

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Threading.Tasks;
      using Microsoft.AspNetCore.Builder;
      using Microsoft.AspNetCore.Hosting;
      using Microsoft.AspNetCore.Mvc;
      using Microsoft.Extensions.Configuration;
      using Microsoft.Extensions.DependencyInjection;
      using Microsoft.Extensions.Logging;
      using Microsoft.Extensions.Options;
      
      namespace SignalRWebApp
      {
          public class Startup
          {
              public Startup(IConfiguration configuration)
              {
                  Configuration = configuration;
              }
      
              public IConfiguration Configuration { get; }
      
              // This method gets called by the runtime. Use this method to add services to the container.
              public void ConfigureServices(IServiceCollection services)
              {
                  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
      
                  services.AddCors(option =>
                  {
                      option.AddPolicy("CorsPolicy", builder =>
                               builder.WithOrigins("http://localhost:4200")
                              .AllowAnyMethod()
                              .AllowAnyHeader()
                              .AllowCredentials());
                  });
                  services.AddSignalR();
              }
      
              // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
              public void Configure(IApplicationBuilder app, IHostingEnvironment env)
              {
                  if (env.IsDevelopment())
                  {
                      app.UseDeveloperExceptionPage();
                  }
      
                  app.UseCors("CorsPolicy");
      
                  app.UseSignalR(routes =>
                  {
                      routes.MapHub<SignalRHub>("/chathub");
                  });
      
                  app.UseHttpsRedirection();
                  app.UseMvc();
              }
          }
      }
      

      SignalRHub.cs

      using Microsoft.AspNetCore.SignalR;
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Threading.Tasks;
      
      namespace SignalRWebApp
      {
          public class SignalRHub : Hub
          {
              public void GetDataFromClient(string userId, string connectionId)
              {
                  Clients.Client(connectionId).SendAsync("clientMethodName", $"Updated userid {userId}");
              }
      
              public override Task OnConnectedAsync()
              {
                  var connectionId = Context.ConnectionId;
                  Clients.Client(connectionId).SendAsync("WelcomeMethodName", connectionId);
                  return base.OnConnectedAsync();
              }
      
              public override Task OnDisconnectedAsync(Exception exception)
              {
                  var connectionId = Context.ConnectionId;
                  return base.OnDisconnectedAsync(exception);
              }
          }
      }
      
      • Angular 示例应用

      安装 signalR 包

      npm install @aspnet/signalr --save

      import { Component, OnInit } from '@angular/core';
      import { HubConnection } from '@aspnet/signalr';
      import * as signalR from '@aspnet/signalr';
      
      @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.scss']
      })
      export class AppComponent implements OnInit {
      
        private hubConnection: HubConnection;
      
        public ngOnInit() {
          this.hubConnection = new signalR.HubConnectionBuilder()
            .withUrl("http://localhost:8080/chathub").build();
      
          this.hubConnection.start().then(() => {
            console.log("connection started");
          }).catch(err => console.log(err));
      
          this.hubConnection.onclose(() => {
            debugger;
            setTimeout(() => {
              debugger;
              this.hubConnection.start().then(() => {
                debugger;
                console.log("connection started");
              }).catch(err => console.log(err));
            }, 5000);
          });
      
          this.hubConnection.on("clientMethodName", (data) => {
            debugger;
            console.log(data);
          });
      
          this.hubConnection.on("WelcomeMethodName", (data) => {
            debugger;
            console.log(data);
            this.hubConnection.invoke("GetDataFromClient", "user id", data).catch(err => console.log(err));
          });
        }
      
        public stopConnection() {
          this.hubConnection.start().then(() => {
            console.log("stopped");
          }).catch(err => console.log(err));
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-07
        • 1970-01-01
        • 1970-01-01
        • 2016-07-23
        • 2019-09-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多