您现在的位置是: 首页 >  .NET CORE >  文章详情 文章详情

ASP.NET Core 集成 WebSocket

2019-08-19 【.NET CORE】 1863人浏览

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



很赞哦! (0)

站长推荐

0.135672s