1

What is the proper way to access IUrlHelper from my SignalR Hub class (ASP.Net Core 2.1)?

I am trying to generate the links to different actions dynamically inside Hub class.

Mohammed Noureldin
  • 14,913
  • 17
  • 70
  • 99

1 Answers1

1

You cannot. UrlHelper requires an ActionContext instance to create URLs, which only exists within the context of a request. A SignalR hub exists outside of the request pipeline. Instead, you should pass the URL into the appropriate hub method from someplace where UrlHelper does exist, like a controller action, instead of relying on the hub to generate it.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • But my links are being generated depending on SignalR messages, I saw different answers where that was possible until .Net Core 2.0, but with 2.1 it seems to not be working anymore. – Mohammed Noureldin Jun 18 '18 at 15:01
  • I don't see that as *ever* being possible, as the hub has never been part of the request pipeline. – Chris Pratt Jun 18 '18 at 15:06
  • This is an example of what I have found, what do you think about it? https://stackoverflow.com/questions/37322076/injection-of-iurlhelper-in-asp-net-core-1-0-rc2. This is not necesserily SignalR case, but they inject the IUrlHelper and the ActionContext (which does not work for me, as the ActionContext is null) – Mohammed Noureldin Jun 18 '18 at 15:11
  • 2
    Because it is then assumed that you're using the example service class *within the request pipeline*, where `ActionContext` actually exists. If you tried to use this service class in something like a regular console app, it would fail as well. `ActionContext` is null in your hub, because, again, the hub is not part of the request pipeline. – Chris Pratt Jun 18 '18 at 15:16
  • Ok I understand thank you. Could you please show a simple code of your last sentence? *nstead, you should pass the URL into the appropriate hub method from someplace where UrlHelper does exist, like a controller action, instead of relying on the hub to generate it.* Because I couldn't have a good imagination of how can this be done. – Mohammed Noureldin Jun 18 '18 at 15:20
  • Can confirm that this doesn't work on ASP.NET Core 2.1. [It seems that there was a workaround for the old ASP.NET Core 4.x](https://stackoverflow.com/a/20432076/3276634) with some kind if fake context. Seems not working on .NET Core since the used classes like `HttpRequest` or `HttpContext` are abstract. Isn't there a similar way in .NET Core 2.1? – Lion Aug 18 '19 at 15:13