public static IApplicationBuilder UseMqttEndpoint(this IApplicationBuilder app, string path = "/mqtt") { app.UseWebSockets(); app.Use(async(context, next) => { if (!context.WebSockets.IsWebSocketRequest || context.Request.Path != path) { await next(); return; } string subProtocol = null; if (context.Request.Headers.TryGetValue("Sec-WebSocket-Protocol", out var requestedSubProtocolValues)) { subProtocol = MqttSubProtocolSelector.SelectSubProtocol(requestedSubProtocolValues); } var adapter = app.ApplicationServices.GetRequiredService <MqttWebSocketServerAdapter>(); using (var webSocket = await context.WebSockets.AcceptWebSocketAsync(subProtocol).ConfigureAwait(false)) { await adapter.RunWebSocketConnectionAsync(webSocket, context); } }); return(app); }
static void ConfigureMqttWebSocketEndpoint(IApplicationBuilder app, MqttService mqttService) { app.Use(async(context, next) => { if (context.Request.Path == "/mqtt") { if (context.WebSockets.IsWebSocketRequest) { string subProtocol = null; if (context.Request.Headers.TryGetValue("Sec-WebSocket-Protocol", out var requestedSubProtocolValues)) { subProtocol = MqttSubProtocolSelector.SelectSubProtocol(requestedSubProtocolValues); } using (var webSocket = await context.WebSockets.AcceptWebSocketAsync(subProtocol).ConfigureAwait(false)) { await mqttService.RunWebSocketConnectionAsync(webSocket, context).ConfigureAwait(false); } } else { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; } } else { await next().ConfigureAwait(false); } }); }
static void ConfigureWebSocketEndpoint( IApplicationBuilder application, MqttServerService mqttServerService, MqttSettingsModel mqttSettings) { if (mqttSettings?.WebSocketEndPoint?.Enabled != true) { return; } if (string.IsNullOrEmpty(mqttSettings.WebSocketEndPoint.Path)) { return; } var webSocketOptions = new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(mqttSettings.WebSocketEndPoint.KeepAliveInterval), ReceiveBufferSize = mqttSettings.WebSocketEndPoint.ReceiveBufferSize }; if (mqttSettings.WebSocketEndPoint.AllowedOrigins?.Any() == true) { webSocketOptions.AllowedOrigins.AddRange(mqttSettings.WebSocketEndPoint.AllowedOrigins); } application.UseWebSockets(webSocketOptions); application.Use(async(context, next) => { if (context.Request.Path == mqttSettings.WebSocketEndPoint.Path) { if (context.WebSockets.IsWebSocketRequest) { string subProtocol = null; if (context.Request.Headers.TryGetValue("Sec-WebSocket-Protocol", out var requestedSubProtocolValues)) { subProtocol = MqttSubProtocolSelector.SelectSubProtocol(requestedSubProtocolValues); } using (var webSocket = await context.WebSockets.AcceptWebSocketAsync(subProtocol).ConfigureAwait(false)) { await mqttServerService.RunWebSocketConnectionAsync(webSocket, context).ConfigureAwait(false); } } else { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; } } else { await next().ConfigureAwait(false); } }); }