在ASP .NET MVC Core应用程序中使用SignalR时,有时需要从SignalR hub中重定向到MVC控制器。以下是一个示例代码,可在Hub类中实现这种重定向。
private readonly IHttpContextAccessor _httpContextAccessor;
public MyHub(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public async Task Redirect()
{
var httpContext = _httpContextAccessor.HttpContext;
httpContext.Response.Redirect("/Home/Index");
}
public void ConfigureServices(IServiceCollection services)
{
// Add SignalR
services.AddSignalR();
services.AddSingleton();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Use SignalR
app.UseEndpoints(endpoints =>
{
endpoints.MapHub("/myhub");
});
}
public IActionResult Index()
{
return View("Index");
}
这样,当调用MyHub重定向到Home/Index操作时,将显示与MVC控制器Index操作相关联的视图。