I am trying out signalR with a simple blog poster and i am unsure as to what would be best practice in implementing it.
First Solution: Have the client invoke the post method on the server which will in turn either supply the data to the relevant web api or other method of uploading the data. my intention here to use the already open connection.
public class BlogHub : Hub
{
public void Post(string text)
{
//Internal Webapi call / other method of DB Update.
Clients.All.BroadcastPost(text);
}
}
Second Solution: Have the client do a ajax call to a web api which then calls the post method and broadcasts it back to the client.
public void PostPost(string text) //May have to call this method something different...
{
db.posts.add(new PostModel(text));
db.SaveChanges();
Post(string Text);
}
third solution: Another (probably better) method i haven't thought of.
fourth Solution: I'm horribly abusing how signalR should be used.
Thanks in advance!
You should use whatever is the most direct way of satisfying your requirements. That said, calling a WebAPI action from a SignalR hub or vice versa is not a good approach. WebAPI actions and Hub methods provide an interface for a specific type of communication. Any internal calls should then go to specific classes which handle your business logic. You can access your hub context in those classes with GlobalHost.ConnectionManager.GetHubContext<MyHub>();
See the hub documentation for an example.
As long as you're only talking about strings and other data which can be serialized to JSON effectively, I don't see why you would need to involve WebAPI at all. If the work you need to do in your hub method is (potentially) long-running (e.g. a DB call), you can make the hub method asynchronous by returning a Task
so it doesn't block the SignalR connection.
If, however, you want to upload binary data (images etc.), it would make sense to upload this to a WebAPI action. Note that you cannot call a hub method directly; instead (as I said above) you should factor out the code that updates all clients to a separate shared class which you then can call from your action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With