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.

ApplicationBuilderExtensions.cs 1.3 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using System;
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using MQTTnet.Core.Server;
  5. namespace MQTTnet.AspNetCore
  6. {
  7. public static class ApplicationBuilderExtensions
  8. {
  9. public static IApplicationBuilder UseMqttEndpoint(this IApplicationBuilder app, string path = "/mqtt")
  10. {
  11. app.UseWebSockets();
  12. app.Use(async (context, next) =>
  13. {
  14. if (context.Request.Path == path && context.WebSockets.IsWebSocketRequest)
  15. {
  16. var adapter = app.ApplicationServices.GetRequiredService<MqttWebSocketServerAdapter>();
  17. using (var webSocket = await context.WebSockets.AcceptWebSocketAsync("mqtt"))
  18. {
  19. await adapter.AcceptWebSocketAsync(webSocket);
  20. }
  21. }
  22. else
  23. {
  24. await next();
  25. }
  26. });
  27. return app;
  28. }
  29. public static IApplicationBuilder UseMqttServer(this IApplicationBuilder app, Action<IMqttServer> configure)
  30. {
  31. var server = app.ApplicationServices.GetRequiredService<IMqttServer>();
  32. configure(server);
  33. return app;
  34. }
  35. }
  36. }