How to connect Hub if Hub is in different project

2019-07-23 16:17发布

问题:

I'm working with SignalR project, in which I want to use Hub in WebApi project as well as Web project. So I've created one class library project and implemented Hub over there.

My project structure looks like:

-ChatHub
  -Hub
-Webapi
-Website 

Here is my Hub:

[HubName("chathub")]
public class ChatHub : Hub
{
   public override Task OnConnected()
   {
       return base.OnConnected();
   }

   public override Task OnReconnected()
   {
       return base.OnReconnected();
   }   
}

When I calling Hub from my website it's working well.

 <script src="~/signalr/hubs"></script>
 var chatHub = $.connection.chathub; 

Here is how I connect Hub from outside(Android):

mHubConnection = new HubConnection(http://{IpAddress}/ChatApp/);
mHubProxy = mHubConnection.createHubProxy(chathub);

API:

public IHttpActionResult LoginUser([FromBody]LoginModel model)
{
  var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();   
  //chatUser logic here
  hubContext.Clients.Client(chatUser.ConnectionId).receiver(response);
}

But it gives me an error:

java.util.concurrent.ExecutionException: microsoft.aspnet.signalr.client.transport.NegotiationException: There was a problem in the negotiation with the server 10-13 18:15:54.074 18686-18686/com.chatapp.android W/System.err: Caused by: microsoft.aspnet.signalr.client.http.InvalidHttpStatusCodeException: Invalid status code: 404

How can we connect Hub if my Hub is out side of API project?

I've gone through Sharing a SignalR hub between a WebApi and MVC project but didn't get the answer they were provided.

回答1:

Are you calling mHubConnection.Start() after setting up the connection and the proxy to the hub? Also is the url being passed into the HubConnection constructor the correct location for the hub? Here are a couple of links that might be helpful, if you haven't already been through them: Access hub from .NET client, configure signalr url