119

I have a single page web app developed using ASP.NET. I recently converted many of the web methods to be push based, using the SignalR library. This really sped up the page considerably and reduced a lot of the server calls from the page.

At the same time, I've also been looking at the RESTful ASP.NET WebAPI for some of the server-side methods, with the real beauty being that it allows to create an API for external applications at the same time that I develop the core application (which will be important for what I'm doing).

It seems however, after looking at several articles and these two questions, that push and WebAPI methods seem like two entirely different paradigms for client-server communication. I'm sure that I can create various methods that can be accessed via either protocol, but I'm uncertain if there are pitfalls to this or if this is considered sloppy -- maybe there's a more elegant way to achieve what I'm aiming for.

There are certainly situations in which I want the RESTful WebAPI to broadcast events via a SignalR hub... The opposite (SignalR ever needing to access the WebAPI) seems less likely, but I suppose still possible.

Has anyone done this? Does anyone have any advice or tips on how to proceed? What would be the most elegant way forward here?

4

3 に答える 3

89

Take a look at the video from this blog post. It explains exactly how you can use WebAPI with SignalR.

Essentially, Web API + SignalR integration consists in this class:

public abstract class ApiControllerWithHub<THub> : ApiController
    where THub : IHub
{
    Lazy<IHubContext> hub = new Lazy<IHubContext>(
        () => GlobalHost.ConnectionManager.GetHubContext<THub>()
    );

    protected IHubContext Hub
    {
        get { return hub.Value; }
    }
}

That's all. :)

于 2012-09-11T12:26:09.947 に答える
18

SignalRは、実際にはすでにWebAPIソースvNext(4.1)に組み込まれています。

RTMビルドを使用せず、代わりにCodeplexからビルドを取得する場合は、そこに新しいプロジェクトがあり、System.Web.Http.SignalRそれを利用できます。数日前にこのコミットで追加されました-http://aspnetwebstack.codeplex.com/SourceControl/changeset/7605afebb159

使用例(コミットに記載されているとおり):

public class ToDoListController : HubController<ToDoListHub>
{
    private static List<string> _items = new List<string>();

    public IEnumerable<string> Get()
    {
        return _items;
    }

    public void Post([FromBody]string item)
    {
        _items.Add(item);
        // Call add on SignalR clients listening to the ToDoListHub
        Clients.add(item);
    }
}

今のところvNextに切り替えたくない場合は、いつでもそのコードを参照用に使用できます。

この実装は、ブラッドウィルソンがNDCオスロで示したものと非常に似ています(もう少し洗練されており、テストなどが含まれています) -http: //vimeo.com/43603472

于 2012-09-11T12:28:43.770 に答える
3

Here is a video showing an integration of the two technologies http://channel9.msdn.com/Events/TechDays/Belgium-2013/25 and here there is a NuGet package for the integration https://www.nuget.org/packages/Microsoft.AspNet.WebApi.SignalR/

于 2013-10-15T07:31:27.357 に答える