Install-Package Microsoft.AspNetCore.WebSockets
在 Startup 类的 Configure 方法中添加 WebSocket 中间件,web
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); //Be sure to configure before mvc middleware. //var webSocketOptions = new WebSocketOptions() //{ // KeepAliveInterval = TimeSpan.FromSeconds(120), // ReceiveBufferSize = 4 * 1024 //}; //app.UseWebSockets(webSocketOptions); app.Use(async (context, next) => { if (context.WebSockets.IsWebSocketRequest) { using (IServiceScope scope = app.ApplicationServices.CreateScope()) { //do something WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); ProcessWebSocketRequest(webSocket); } } else { //Hand over to the next middleware await next(); } }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
必定要在MVC中间件以前配置WebSocket中间件,不然没法接受到WebSocket请求websocket
编写具体业务代码mvc
部署运行项目app
至此就完成了AspNetCore MVC集成 WebSocketsocket
app.UseWebSockets();必定要在 app.UserMVC()以前配置async
使用自定义中间件优先处理WebSocket请求ui
AspNetCoreWithWebSocketDemo.7zcode