ASP.NET Core 集成 WebSocket

1. 环境

  • AspNetCore Web 2.0 (MVC)
  • Windows 10
  • IIS 10 Express/IIS
  • VS 2017

2.如何配置

  1. 在已有的或者新创建的 AspNet Core MVC 项目中安装 Microsoft.AspNetCore.WebSockets
    Install-Package  Microsoft.AspNetCore.WebSockets 
  1. 配置中间件

Startup 类的 Configure 方法中添加 WebSocket 中间件,

    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请求

  1. 编写具体业务代码

  2. 部署运行项目

至此就完成了AspNetCore MVC集成 WebSocket

Tips

  1. app.UseWebSockets();一定要在 app.UserMVC()之前配置

  2. 使用自定义中间件优先处理WebSocket请求

完整示例

AspNetCoreWithWebSocketDemo.7z

参考资料

ASP.NET Core 中的 WebSocket 支持

posted @ 2018-10-22 22:41  betterme  阅读(7282)  评论(0编辑  收藏  举报