Home > Software engineering >  ASP .NET MVC Core SignalR: Redirecting from a Hub to a Controller
ASP .NET MVC Core SignalR: Redirecting from a Hub to a Controller

Time:01-05

Question

Is it possible to redirect a user from a SignalR Core Hub to any other location within my application?

I tried using GetHttpContext and then invoking Response.Redirect, but I get an exception informing that the Response has already been started.

More context

I use MVC in my application to get a simple controller for routing and for using the MVC cookie-based authentication. Then on successful authentication a user gets redirected by my Controller to a location governed by a SignalR Hub. However, I noticed that in some situation I need to return user to login page based on the information in my Hub.

Does it make sense or maybe I made a mistake while designing my application and need to rework it now?

CodePudding user response:

As @Wiktor Zychla said, we should do these things at client-side, since the server hub's method couldn't redirect the client. You could only write the method at the server and then do the redirect by using the client js.

More details, you could refer to below codes:

    public async Task RedirectPage(string user) {
        // You could send it to a specific user
        await Clients.All.SendAsync("RedirectPageClient", "home/index");
    }

Js codes:

           connection.on("RedirectPageClient",function(url){
           
              console.log(url);
              window.location.href = url;
      
           });
  •  Tags:  
  • Related