1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- using System;
- using System.Collections.Generic;
- using System.Net.Http;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Http;
- namespace IoTIntegrationPlatform.Common
- {
- public static class HttpManager
- {
- /// <summary>
- /// 获取用户ip地址
- /// </summary>
- /// <param name="httpContextAccessor"></param>
- /// <returns></returns>
- public static string GetUserIP(IHttpContextAccessor httpContextAccessor)
- {
- var Request = httpContextAccessor.HttpContext.Request;
- string realIP = null;
- string forwarded = null;
- string remoteIpAddress = httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
- if (Request.Headers.ContainsKey("X-Real-IP"))
- {
- realIP = Request.Headers["X-Real-IP"].ToString();
- if (realIP != remoteIpAddress)
- {
- remoteIpAddress = realIP;
- }
- }
- if (Request.Headers.ContainsKey("X-Forwarded-For"))
- {
- forwarded = Request.Headers["X-Forwarded-For"].ToString();
- if (forwarded != remoteIpAddress)
- {
- remoteIpAddress = forwarded;
- }
- }
- return remoteIpAddress;
- }
- /// <summary>
- /// Http异步发送
- /// </summary>
- /// <param name="httpClientFactory"></param>
- /// <param name="method"></param>
- /// <param name="url"></param>
- /// <param name="headers"></param>
- /// <returns></returns>
- public static async Task<string> HttpSendAsync(this IHttpClientFactory httpClientFactory, HttpMethod method, string url, Dictionary<string, string> headers = null)
- {
- var client = httpClientFactory.CreateClient();
- var content = new StringContent("");
- // content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
- var request = new HttpRequestMessage(method, url)
- {
- Content = content
- };
- if (headers != null)
- {
- foreach (var header in headers)
- {
- request.Headers.Add(header.Key, header.Value);
- }
- }
- try
- {
- HttpResponseMessage httpResponseMessage = await client.SendAsync(request);
- var result = await httpResponseMessage.Content
- .ReadAsStringAsync();
- return result;
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- return ex.Message;
- }
- }
- }
- }
|