A, Js end
@{ 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 the src = "~ / lib / SignalR / dist / Browser / signalr.js" > </ Script > < Script type = "text / JavaScript" > " use strict " ; var URL = " / chatHub " ; // local site can directly write" / Chat " var loginToken = " token " ; // the JWT verification code. Without Bearer var Connection = new new signalR.HubConnectionBuilder (). WithUrl (URL,=> 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>
Two, Startup.cs arranged end
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 new JwtBearerEvents { OnMessageReceived = (context) => { IF (! Context.HttpContext.Request.Path.HasValue) { return Task.CompletedTask; } // focus here; Analyzing the path of Signalr var accessToken = context.HttpContext. Request.Query [ " the 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 (); }); // default static resource path wwwroot app.UseStaticFiles (); // default to start the cookie app.UseCookiePolicy (); // add an authorized service app.UseAuthentication (); // configuration app. UseSignalR (= routes> // 2, reference { // SignalrHub Hub inherited class code for the background, "/ chatHub" as request routing address; routes.MapHub <chatHub> ( " / chatHub " ); }); // start MVC app.UseMvc (routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }