Index.cshtml.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.AspNetCore.Mvc.RazorPages;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.Logging;
  6. using Vote.Messaging;
  7. using Vote.Messaging.Messages;
  8. namespace Vote.Pages
  9. {
  10. public class IndexModel : PageModel
  11. {
  12. private string _optionA;
  13. private string _optionB;
  14. protected readonly IMessageQueue _messageQueue;
  15. protected readonly IConfiguration _configuration;
  16. protected readonly ILogger _logger;
  17. public IndexModel(IMessageQueue messageQueue, IConfiguration configuration, ILogger<IndexModel> logger)
  18. {
  19. _messageQueue = messageQueue;
  20. _configuration = configuration;
  21. _logger = logger;
  22. _optionA = _configuration.GetValue<string>("Voting:OptionA");
  23. _optionB = _configuration.GetValue<string>("Voting:OptionB");
  24. }
  25. public string OptionA { get; private set; }
  26. public string OptionB { get; private set; }
  27. [BindProperty]
  28. public string Vote { get; private set; }
  29. private string _voterId
  30. {
  31. get { return TempData.Peek("VoterId") as string; }
  32. set { TempData["VoterId"] = value; }
  33. }
  34. public void OnGet()
  35. {
  36. OptionA = _optionA;
  37. OptionB = _optionB;
  38. }
  39. public IActionResult OnPost(string vote)
  40. {
  41. Vote = vote;
  42. OptionA = _optionA;
  43. OptionB = _optionB;
  44. if (_configuration.GetValue<bool>("MessageQueue:Enabled"))
  45. {
  46. PublishVote(vote);
  47. }
  48. return Page();
  49. }
  50. private void PublishVote(string vote)
  51. {
  52. if (string.IsNullOrEmpty(_voterId))
  53. {
  54. _voterId = Guid.NewGuid().ToString();
  55. }
  56. var message = new VoteCastEvent
  57. {
  58. VoterId = _voterId,
  59. Vote = vote
  60. };
  61. _messageQueue.Publish(message);
  62. }
  63. }
  64. }