如何使用Signalr以角度读取从Web API发送的数据?

时间:2019-07-18 05:26:54

标签: angular asp.net-web-api signalr

我想读取通过角度客户端中的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();

在角度客户端中,

    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);
    });
  }

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

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

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我得到了答案:

我的新中心(在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);
        }
    }

以及在Angle Client(使用Signalr)中:

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
  }

答案 2 :(得分:0)

Github

  • 具有 netcoreapp2.2

    的Web API

    安装 Microsoft.AspNetCore.SignalR

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

String str = "value1, value2"
String first;
String second;

//code

if (first.equals("value1") && second.equals("value2") {
   System.out.println("Success!!)";
}

Startup.cs

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

[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";
        }
    }
}

SignalRHub.cs

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();
        }
    }
}
  • 角度示例应用程序

安装signalR软件包

npm install @ aspnet / signalr-保存

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);
        }
    }
}