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.
 
 
 
 

43 lines
1.3 KiB

  1. using System;
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using MQTTnet.AspNetCore;
  5. using MQTTnet.Core.Server;
  6. namespace MQTTnet.AspnetCore
  7. {
  8. public static class ApplicationBuilderExtensions
  9. {
  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.Request.Path == path && context.WebSockets.IsWebSocketRequest)
  16. {
  17. var adapter = app.ApplicationServices.GetRequiredService<MqttWebSocketServerAdapter>();
  18. using (var webSocket = await context.WebSockets.AcceptWebSocketAsync("mqtt"))
  19. {
  20. await adapter.AcceptWebSocketAsync(webSocket);
  21. }
  22. }
  23. else
  24. {
  25. await next();
  26. }
  27. });
  28. return app;
  29. }
  30. public static IApplicationBuilder UseMqttServer(this IApplicationBuilder app, Action<IMqttServer> configure)
  31. {
  32. var server = app.ApplicationServices.GetRequiredService<IMqttServer>();
  33. configure(server);
  34. return app;
  35. }
  36. }
  37. }