ASP.NET Core 集成 WebSocket
1. 环境
- AspNetCore Web 2.0 (MVC)
- Windows 10
- IIS 10 Express/IIS
- VS 2017
2.如何配置
- 在已有的或者新创建的 AspNet Core MVC 项目中安装 Microsoft.AspNetCore.WebSockets 包
Install-Package Microsoft.AspNetCore.WebSockets
- 配置中间件
在 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请求
-
编写具体业务代码
-
部署运行项目
至此就完成了AspNetCore MVC集成 WebSocket
Tips
-
app.UseWebSockets();一定要在 app.UserMVC()之前配置
-
使用自定义中间件优先处理WebSocket请求
完整示例
AspNetCoreWithWebSocketDemo.7z