Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

53 rader
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. }