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 2.0 KiB

7 vuotta sitten
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using System.Linq;
  5. using MQTTnet.Server;
  6. using System.Collections.Generic;
  7. namespace MQTTnet.AspNetCore
  8. {
  9. public static class ApplicationBuilderExtensions
  10. {
  11. public static IApplicationBuilder UseMqttEndpoint(this IApplicationBuilder app, string path = "/mqtt")
  12. {
  13. app.UseWebSockets();
  14. app.Use(async (context, next) =>
  15. {
  16. if (!context.WebSockets.IsWebSocketRequest || context.Request.Path != path)
  17. {
  18. await next();
  19. return;
  20. }
  21. string subProtocol = null;
  22. if (context.Request.Headers.TryGetValue("Sec-WebSocket-Protocol", out var requestedSubProtocolValues))
  23. {
  24. subProtocol = SelectSubProtocol(requestedSubProtocolValues);
  25. }
  26. var adapter = app.ApplicationServices.GetRequiredService<MqttWebSocketServerAdapter>();
  27. using (var webSocket = await context.WebSockets.AcceptWebSocketAsync(subProtocol))
  28. {
  29. var endpoint = $"{context.Connection.RemoteIpAddress}:{context.Connection.RemotePort}";
  30. await adapter.RunWebSocketConnectionAsync(webSocket, endpoint);
  31. }
  32. });
  33. return app;
  34. }
  35. public static string SelectSubProtocol(IList<string> requestedSubProtocolValues)
  36. {
  37. // Order the protocols to also match "mqtt", "mqttv-3.1", "mqttv-3.11" etc.
  38. return requestedSubProtocolValues
  39. .OrderByDescending(p => p.Length)
  40. .FirstOrDefault(p => p.ToLower().StartsWith("mqtt"));
  41. }
  42. public static IApplicationBuilder UseMqttServer(this IApplicationBuilder app, Action<IMqttServer> configure)
  43. {
  44. var server = app.ApplicationServices.GetRequiredService<IMqttServer>();
  45. configure(server);
  46. return app;
  47. }
  48. }
  49. }