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.
 
 
 
 

53 lines
1.9 KiB

  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using Microsoft.AspNetCore.Builder;
  6. using Microsoft.Extensions.DependencyInjection;
  7. using MQTTnet.Server;
  8. namespace MQTTnet.AspNetCore
  9. {
  10. public static class ApplicationBuilderExtensions
  11. {
  12. [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(...).")]
  13. public static IApplicationBuilder UseMqttEndpoint(this IApplicationBuilder app, string path = "/mqtt")
  14. {
  15. app.UseWebSockets();
  16. app.Use(async (context, next) =>
  17. {
  18. if (!context.WebSockets.IsWebSocketRequest || context.Request.Path != path)
  19. {
  20. await next();
  21. return;
  22. }
  23. string subProtocol = null;
  24. if (context.Request.Headers.TryGetValue("Sec-WebSocket-Protocol", out var requestedSubProtocolValues))
  25. {
  26. subProtocol = MqttSubProtocolSelector.SelectSubProtocol(requestedSubProtocolValues);
  27. }
  28. var adapter = app.ApplicationServices.GetRequiredService<MqttWebSocketServerAdapter>();
  29. using (var webSocket = await context.WebSockets.AcceptWebSocketAsync(subProtocol).ConfigureAwait(false))
  30. {
  31. await adapter.RunWebSocketConnectionAsync(webSocket, context);
  32. }
  33. });
  34. return app;
  35. }
  36. public static IApplicationBuilder UseMqttServer(this IApplicationBuilder app, Action<MqttServer> configure)
  37. {
  38. var server = app.ApplicationServices.GetRequiredService<MqttServer>();
  39. configure(server);
  40. return app;
  41. }
  42. }
  43. }