HttpTrigger.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. 
  2. using Newtonsoft.Json.Linq;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Net.Http;
  7. using System.Reflection;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Security.Cryptography;
  11. using System.Net.Http.Json;
  12. using System.Text.Json;
  13. using System.IO;
  14. using TEAMModelOS.SDK.Extension;
  15. using System.Net;
  16. using TEAMModelOS.SDK.Models;
  17. namespace TEAMModelOS.SDK.DI
  18. {
  19. public class HttpTrigger
  20. {
  21. private readonly HttpClient _httpClient;
  22. public HttpTrigger(HttpClient httpClient)
  23. {
  24. _httpClient = httpClient;
  25. }
  26. // <summary>
  27. /// 请求信息
  28. /// </summary>
  29. /// <param name="robotUrl">釘釘Robot發送Url</param>
  30. /// <param name="secret">加簽密鑰</param>
  31. /// <param name="msg">發送訊息</param>
  32. /// <returns></returns>
  33. public async Task<(int status, string json)> RequestHttpTrigger(object data, string location, string url)
  34. {
  35. var keys = HttpTriggerUrl.HttpTrigger地址.GetDescriptionText().Split(',');
  36. string domain = "";
  37. if (location.Equals("China-Dep"))
  38. {
  39. domain = keys[0];
  40. }
  41. else if (location.Equals("China-Test"))
  42. {
  43. domain = keys[1];
  44. }
  45. else if (location.Equals("China"))
  46. {
  47. domain = keys[2];
  48. }
  49. else if (location.Equals("Global-Dep"))
  50. {
  51. domain = keys[3];
  52. }
  53. else if (location.Equals("Global-Test"))
  54. {
  55. domain = keys[3];
  56. }
  57. else if (location.Equals("Global"))
  58. {
  59. domain = keys[4];
  60. }
  61. string link = domain.Contains("localhost") ? $"http://{domain}/api/{url}" : $"https://{domain}/api/{url}";
  62. HttpContent httpContent = new StringContent(data.ToJsonString());
  63. // _httpClient.Timeout= TimeSpan.FromSeconds(30);
  64. HttpResponseMessage responseMessage = await _httpClient.PostAsync(link, httpContent);
  65. if (responseMessage.StatusCode == HttpStatusCode.OK)
  66. {
  67. string Content = await responseMessage.Content.ReadAsStringAsync();
  68. if (string.IsNullOrWhiteSpace(Content))
  69. {
  70. return (200, null) ;
  71. }
  72. else {
  73. Content.ToObject<JsonElement>().TryGetProperty("data", out JsonElement content);
  74. return (200, $"{content}");
  75. }
  76. }
  77. else
  78. {
  79. string Content = await responseMessage.Content?.ReadAsStringAsync();
  80. return (500, Content);
  81. }
  82. }
  83. }
  84. public enum HttpTriggerUrl
  85. {
  86. [Description("localhost:7071,teammodelosfunction-test.chinacloudsites.cn,teammodelosfunction.chinacloudsites.cn,localhost:7071,teammodelfunction.azurewebsites.net")]
  87. HttpTrigger地址,
  88. }
  89. }