calling SignalR hub from WebAPI controller issues

匿名 (未验证) 提交于 2019-12-03 01:08:02

问题:

I cannot figure out how I can call into a SignalR hub from a WebAPI ApiController. I have put together a sample you can download here that simplifies the problem and demonstrates the issue.

  1. I created a new project from the ASP.NET MVC WebAPI template.
  2. I added a new SignalR Hub to the project called ChatHub.
  3. Added a HTML page that on load, connects to ChatHub, joins to a group and sends a message to that group. This works great.
  4. HTML page also has a button that when clicked will fire an ajax call to the ValuesController's post method. In the ValuesController's post method, I want to broadcast a message to all the connected clients of the group. I cannot get this to work.

I have a simple SignalR hub with just 2 methods.

[HubName("chat")] public class ChatHub : Hub {     public void Join(string room)     {         // NOTE: this is not persisted - ....         Groups.Add(Context.ConnectionId, room);     }      public void Send(string room, string message)     {         var msg = String.Format(             "{0}: {1}", Context.ConnectionId, message);         Clients.Group(room).newMessage(msg);     } } 

I created a very simple HTML page that connects to the Chat hub when the DOM is ready as shown here.

      Simple Chat

Chat

Message(s) Received

    Nothing fancy. Whenever the connected hub receives a new message, a new item is added to the unordered list. There is a button that makes an Ajax call into the ValuesController post method.

    public class ValuesController : ApiController {     // POST api/values     public void Post([FromBody]string value)     {         var hubContext = GlobalHost.ConnectionManager.GetHubContext();         hubContext.Clients.Group("TestGroup").send("TestGroup", "Called from Controller");     } 

    The Hub call does not work. An error is not thrown, but, the message is never received. Putting a breakpoint in the "Send" method of the Hub does not work either. I feel like I am doing it right. Anyone help? Again, source code can be found here

    回答1:

    You are calling different methods on the client:

    API controller

    hubContext.Clients.Group("TestGroup").send("TestGroup", "Called from Controller"); 

    Hub

    Clients.Group(room).newMessage(msg); 

    The method you want to call is newMessage not send

    chat.client.newMessage = onNewMessage; 


    标签
    易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!