You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

49 lines
1.8 KiB

  1. using System;
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using MQTTnet.Server;
  5. namespace MQTTnet.AspNetCore.Extensions
  6. {
  7. public static class ApplicationBuilderExtensions
  8. {
  9. [Obsolete("This class is obsolete and will be removed in a future version. The recommended alternative is to use MapMqtt inside Microsoft.AspNetCore.Builder.UseEndpoints(...).")]
  10. public static IApplicationBuilder UseMqttEndpoint(this IApplicationBuilder app, string path = "/mqtt")
  11. {
  12. app.UseWebSockets();
  13. app.Use(async (context, next) =>
  14. {
  15. if (!context.WebSockets.IsWebSocketRequest || context.Request.Path != path)
  16. {
  17. await next();
  18. return;
  19. }
  20. string subProtocol = null;
  21. if (context.Request.Headers.TryGetValue("Sec-WebSocket-Protocol", out var requestedSubProtocolValues))
  22. {
  23. subProtocol = MqttSubProtocolSelector.SelectSubProtocol(requestedSubProtocolValues);
  24. }
  25. var adapter = app.ApplicationServices.GetRequiredService<MqttWebSocketServerAdapter>();
  26. using (var webSocket = await context.WebSockets.AcceptWebSocketAsync(subProtocol).ConfigureAwait(false))
  27. {
  28. await adapter.RunWebSocketConnectionAsync(webSocket, context);
  29. }
  30. });
  31. return app;
  32. }
  33. public static IApplicationBuilder UseMqttServer(this IApplicationBuilder app, Action<IMqttServer> configure)
  34. {
  35. var server = app.ApplicationServices.GetRequiredService<IMqttServer>();
  36. configure(server);
  37. return app;
  38. }
  39. }
  40. }