一、Js端
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </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"> "use strict"; var url = "/chatHub"; //本地站点可以直接写"/chat" var loginToken = "token"; // JWT验证码。不带Bearer var connection = new signalR.HubConnectionBuilder().withUrl(url, { accessTokenFactory: () => loginToken }).build(); //Disable send button until connection is established document.getElementById("sendButton").disabled = true; connection.on("ReceiveMessage", function (user, message) { var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); var encodedMsg = user + " says " + msg; var li = document.createElement("li"); li.textContent = encodedMsg; document.getElementById("messagesList").appendChild(li); }); connection.start().then(function () { document.getElementById("sendButton").disabled = false; }).catch(function (err) { return console.error(err.toString()); }); document.getElementById("sendButton").addEventListener("click", function (event) { var user = document.getElementById("userInput").value; var message = document.getElementById("messageInput").value; connection.invoke("SendMessage", user, message).catch(function (err) { return console.error(err.toString()); }); event.preventDefault(); }); </script> </body> </html>
二、Startup.cs配置端
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; using System; using System.Text; using System.Threading.Tasks; using test.Hubs; //3、引用 处理客户端 - 服务器通信的高级管道 namespace test { 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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //JWT令牌配置 services.AddAuthentication(options => { options.DefaultAuthenticateScheme = "JwtBearer"; options.DefaultChallengeScheme = "JwtBearer"; }).AddJwtBearer("JwtBearer", options => { options.Audience = "Audience"; options.TokenValidationParameters = new TokenValidationParameters { // The signing key must match! ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("SecurityKey")), // Validate the JWT Issuer (iss) claim ValidateIssuer = true, ValidIssuer = "Issuer", // Validate the JWT Audience (aud) claim ValidateAudience = true, ValidAudience = "Audience", // Validate the token expiry ValidateLifetime = true, // If you want to allow a certain Account of clock drift, set that here ClockSkew = TimeSpan.Zero }; options.Events = new JwtBearerEvents { OnMessageReceived = (context) => { if (!context.HttpContext.Request.Path.HasValue) { return Task.CompletedTask; } //重点在于这里;判断是Signalr的路径 var accessToken = context.HttpContext.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!(string.IsNullOrWhiteSpace(accessToken)) && path.StartsWithSegments("/chatHub")) { context.Token = accessToken; return Task.CompletedTask; } return Task.CompletedTask; } }; }); //1、添加服务 services.AddSignalR(); } // 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.UseCors(builder => { builder.SetIsOriginAllowed(origin => true) .AllowAnyHeader() .WithMethods("GET", "POST") .AllowCredentials(); }); //默认静态资源路径wwwroot app.UseStaticFiles(); //默认启动cookie app.UseCookiePolicy(); //添加授权服务 app.UseAuthentication(); //配置 app.UseSignalR(routes => //2、引用 { //SignalrHub为后台代码中继承Hub的类,"/chatHub"为请求路由地址; routes.MapHub<ChatHub>("/chatHub"); }); //启动MVC app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }