I have an ASP.NET Web API server, that have to communicate with different applications on different platforms. And now I want to create a method that would be something like a callback: client application subscribes to it and waits until server fires a message.
Example: Many users are waiting until new product will be available in store - they subscribe to this "event". When product arrives in store - every customer receives a message, which have to be handled in some case.
I tried to find some information about callbacks or duplex in ASP.NET Web API, but the one advice - it's better to use WCF for this approach.
If you have some ideas how i can solve this problem, please give me an advice.
Thanks for help.
A "callback" is a term that refers to a coding design pattern. In this design pattern executable code is passed as an argument to other code and it is expected to call back at some time. This callback can be synchronous or asynchronous.
In a client callback, a client script function sends a request to the ASP.NET Web page, which then runs an abbreviated version of its normal life cycle to process the callback. To ensure that callback events originate from the expected user interface (UI), you can validate callbacks.
A callback is an asynchronous API request that originates from the API server and is sent to the client in response to an earlier request sent by that client. APIs can use callbacks to signal an event of interest and share data related to that event.
think of it as 'sending the server the whole page (asp.net) full of data'. On the other hand, a callback is also a special kind of postback, but it is just a quick round-trip to the server to get a small set of data (normally), and thus the page is not refreshed, unlike with the postback...
Looks like you want push notifications from your server - which, in this case, can be achieved by combining SignalR with Web API.
Brad Wilson has a great example on this:
code here - https://github.com/bradwilson/WebstackOfLove
NDC Oslo talk explaining all this - http://vimeo.com/43603472
In short, whenever you add new item to the Web API, you can notify all the connected (subscribed) clients:
public void PostNewItem(ToDoItem item)
{
lock (db)
{
// Add item to the database
db.Add(item);
// Notify the connected clients
Hub.Clients.processItem(item);
}
}
SignalR will invoke the processItem
function on the client.
Alternatively, you might want to look into JavaScript SSE and Web API PushStreamContent
but that is much more low level and SignalR abstracts a lot of this type of stuff for you so it might be more complicated to deal with.
I blogged about this approach here http://www.strathweb.com/2012/05/native-html5-push-notifications-with-asp-net-web-api-and-knockout-js/
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