HttpManager.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net.Http;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Http;
  6. namespace IoTIntegrationPlatform.Common
  7. {
  8. public static class HttpManager
  9. {
  10. /// <summary>
  11. /// 获取用户ip地址
  12. /// </summary>
  13. /// <param name="httpContextAccessor"></param>
  14. /// <returns></returns>
  15. public static string GetUserIP(IHttpContextAccessor httpContextAccessor)
  16. {
  17. var Request = httpContextAccessor.HttpContext.Request;
  18. string realIP = null;
  19. string forwarded = null;
  20. string remoteIpAddress = httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
  21. if (Request.Headers.ContainsKey("X-Real-IP"))
  22. {
  23. realIP = Request.Headers["X-Real-IP"].ToString();
  24. if (realIP != remoteIpAddress)
  25. {
  26. remoteIpAddress = realIP;
  27. }
  28. }
  29. if (Request.Headers.ContainsKey("X-Forwarded-For"))
  30. {
  31. forwarded = Request.Headers["X-Forwarded-For"].ToString();
  32. if (forwarded != remoteIpAddress)
  33. {
  34. remoteIpAddress = forwarded;
  35. }
  36. }
  37. return remoteIpAddress;
  38. }
  39. /// <summary>
  40. /// Http异步发送
  41. /// </summary>
  42. /// <param name="httpClientFactory"></param>
  43. /// <param name="method"></param>
  44. /// <param name="url"></param>
  45. /// <param name="headers"></param>
  46. /// <returns></returns>
  47. public static async Task<string> HttpSendAsync(this IHttpClientFactory httpClientFactory, HttpMethod method, string url, Dictionary<string, string> headers = null)
  48. {
  49. var client = httpClientFactory.CreateClient();
  50. var content = new StringContent("");
  51. // content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
  52. var request = new HttpRequestMessage(method, url)
  53. {
  54. Content = content
  55. };
  56. if (headers != null)
  57. {
  58. foreach (var header in headers)
  59. {
  60. request.Headers.Add(header.Key, header.Value);
  61. }
  62. }
  63. try
  64. {
  65. HttpResponseMessage httpResponseMessage = await client.SendAsync(request);
  66. var result = await httpResponseMessage.Content
  67. .ReadAsStringAsync();
  68. return result;
  69. }
  70. catch (Exception ex)
  71. {
  72. Console.WriteLine(ex.Message);
  73. return ex.Message;
  74. }
  75. }
  76. }
  77. }