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.

MessagesController.cs 1.5 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using Microsoft.AspNetCore.Authorization;
  5. using Microsoft.AspNetCore.Mvc;
  6. using MQTTnet.Protocol;
  7. using MQTTnet.Server.Mqtt;
  8. namespace MQTTnet.Server.Controllers
  9. {
  10. [Authorize]
  11. [ApiController]
  12. public class MessagesController : Controller
  13. {
  14. private readonly MqttServerService _mqttServerService;
  15. public MessagesController(MqttServerService mqttServerService)
  16. {
  17. _mqttServerService = mqttServerService ?? throw new ArgumentNullException(nameof(mqttServerService));
  18. }
  19. [Route("api/v1/messages")]
  20. [HttpPost]
  21. public async Task<ActionResult> PostMessage(MqttApplicationMessage message)
  22. {
  23. await _mqttServerService.PublishAsync(message);
  24. return Ok();
  25. }
  26. [Route("api/v1/messages/{*topic}")]
  27. [HttpPost]
  28. public async Task<ActionResult> PostMessage(string topic, int qosLevel = 0)
  29. {
  30. byte[] payload;
  31. using (var memoryStream = new MemoryStream())
  32. {
  33. await HttpContext.Request.Body.CopyToAsync(memoryStream);
  34. payload = memoryStream.ToArray();
  35. }
  36. var message = new MqttApplicationMessageBuilder()
  37. .WithTopic(topic)
  38. .WithPayload(payload)
  39. .WithQualityOfServiceLevel((MqttQualityOfServiceLevel)qosLevel)
  40. .Build();
  41. return await PostMessage(message);
  42. }
  43. }
  44. }