获取 IHubContext 的实例
在 ASP.NET Core SignalR,您可以访问的实例IHubContext通过依赖关系注入。 您可以注入的实例IHubContext到控制器、 中间件或其他 DI 服务。 使用的实例将消息发送到客户端。
注入控制器中的 IHubContext 实例有两种方法
一:.直接将实例注入到IHubContext添加到控制器的构造函数:
具体步骤:
1.直接将实例注入到IHubContext添加到控制器的构造函数:
public class HomeController : Controller { private readonly IHubContext<ChatHub> _hubContext; public HomeController(IHubContext<ChatHub> chatHubContext) { _hubContext = chatHubContext; } public async Task<IActionResult> Index() { return View(); } }
2.配置 SignalR
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddSignalR(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseCookiePolicy(); app.UseSignalR(routes => { routes.MapHub<ChatHub>("/chatHub"); }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } }
3.生成Home视图,代码:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,user-scalable=no"> <title>Test</title> <script src="~/lib/jquery/dist/jquery.js"></script> </head> <body > <div class="container"> <div class="row"> </div> <div class="row"> <div class="col-6"> </div> <div class="col-6"> User..........<input type="text" id="userInput" /> <br /> Message...<input type="text" id="messageInput" /> <input type="button" id="sendButton" value="Send Message" /> </div> </div> <div class="row"> <div class="col-12"> <hr /> </div> </div> <div class="row"> <div class="col-6"> </div> <div class="col-6"> <ul id="messagesList"></ul> </div> </div> </div> <script src="~/lib/signalr/dist/browser/signalr.js"></script> <script type="text/javascript"> const connection = new signalR.HubConnectionBuilder() .withUrl("/chatHub") .build(); connection.on("ReceiveMessage", (user, message, id) => { const encodedMsg = user + " says " + message + " id:" + id ; const li = document.createElement("li"); li.textContent = encodedMsg; document.getElementById("messagesList").appendChild(li); }); document.getElementById("sendButton").addEventListener("click", event => { const user = document.getElementById("userInput").value; const message = document.getElementById("messageInput").value; connection.invoke("SendMessage", user, message).catch(err => console.error(err)); event.preventDefault(); }); connection.start().catch(err => console.error(err)); //connection.start(); </script> </body> </html>
4.运行结果:
二:注入强类型化 HubContext
1.将强类型注入到IHubContext添加到控制器的构造函数:
public class HomeController : Controller { // private readonly IHubContext<ChatHub> _hubContext; private IHubContext<StronglyTypedChatHub, IChatClient> _hubContext { get; } public HomeController(IHubContext<StronglyTypedChatHub, IChatClient> chatHubContext) { _hubContext = chatHubContext; } public async Task<IActionResult> Index() { return View(); } }
2.配置 SignalR
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseCookiePolicy(); app.UseSignalR(routes => { routes.MapHub<StronglyTypedChatHub>("/chatHub"); }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
3.生成Home视图,代码:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,user-scalable=no"> <title>Test</title> <script src="~/lib/jquery/dist/jquery.js"></script> </head> <body > <div class="container"> <div class="row"> </div> <div class="row"> <div class="col-6"> </div> <div class="col-6"> User..........<input type="text" id="userInput" /> <br /> Message...<input type="text" id="messageInput" /> <input type="button" id="sendButton" value="Send Message" /> </div> </div> <div class="row"> <div class="col-12"> <hr /> </div> </div> <div class="row"> <div class="col-6"> </div> <div class="col-6"> <ul id="messagesList"></ul> </div> </div> </div> <script src="~/lib/signalr/dist/browser/signalr.js"></script> <script type="text/javascript"> const connection = new signalR.HubConnectionBuilder() .withUrl("/chatHub") .build(); connection.on("ReceiveMessage", (user, message, id) => { const encodedMsg = user + " says " + message + " id:" + id ; const li = document.createElement("li"); li.textContent = encodedMsg; document.getElementById("messagesList").appendChild(li); }); document.getElementById("sendButton").addEventListener("click", event => { const user = document.getElementById("userInput").value; const message = document.getElementById("messageInput").value; connection.invoke("SendMessage", user, message).catch(err => console.error(err)); event.preventDefault(); }); connection.start().catch(err => console.error(err)); //connection.start(); </script> </body> </html>
4.运行结果: