1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
 
namespace VueWebCoreApi.Quartz
{
    public static class HttpManager
    {
        public static string GetUserIP(IHttpContextAccessor httpContextAccessor)
        {
            if (httpContextAccessor?.HttpContext == null)
                return string.Empty;
 
            var request = httpContextAccessor.HttpContext.Request;
            string remoteIpAddress = httpContextAccessor.HttpContext.Connection.RemoteIpAddress?.ToString() ?? string.Empty;
 
            if (request.Headers.ContainsKey("X-Real-IP"))
            {
                var realIp = request.Headers["X-Real-IP"].ToString();
                if (!string.IsNullOrEmpty(realIp) && realIp != remoteIpAddress)
                {
                    remoteIpAddress = realIp;
                }
            }
 
            if (request.Headers.ContainsKey("X-Forwarded-For"))
            {
                var forwarded = request.Headers["X-Forwarded-For"].ToString();
                if (!string.IsNullOrEmpty(forwarded) && forwarded != remoteIpAddress)
                {
                    remoteIpAddress = forwarded;
                }
            }
 
            return remoteIpAddress;
        }
 
        public static async Task<string> HttpSendAsyncString(this IHttpClientFactory httpClientFactory, HttpMethod method, string url, string parameters = null, Dictionary<string, string> headers = null)
        {
            if (httpClientFactory == null)
                throw new ArgumentNullException(nameof(httpClientFactory));
            if (method == null)
                throw new ArgumentNullException(nameof(method));
            if (string.IsNullOrEmpty(url))
                throw new ArgumentNullException(nameof(url));
 
            var client = httpClientFactory.CreateClient();
            string finalUrl = url;
            HttpContent content = new StringContent("");
 
            try
            {
                // ====================== GET 请求:拼接参数到 URL ======================
                if (method == HttpMethod.Get && !string.IsNullOrWhiteSpace(parameters))
                {
                    finalUrl = url.Contains("?")
                        ? $"{url}&{parameters}"
                        : $"{url}?{parameters}";
                }
 
                // ====================== POST 请求:参数放入 Body ======================
                if (method == HttpMethod.Post && !string.IsNullOrWhiteSpace(parameters))
                {
                    content = new StringContent(
                        parameters,
                        System.Text.Encoding.UTF8,
                        "application/x-www-form-urlencoded");
                }
 
                var request = new HttpRequestMessage(method, finalUrl) { Content = content };
 
                // 追加请求头
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        if (!request.Headers.TryAddWithoutValidation(header.Key, header.Value))
                        {
                            content.Headers.TryAddWithoutValidation(header.Key, header.Value);
                        }
                    }
                }
 
                using (var response = await client.SendAsync(request))
                {
                    response.EnsureSuccessStatusCode();
                    return await response.Content.ReadAsStringAsync();
                }
            }
            catch (Exception ex)
            {
                return $"请求失败:{ex.Message}";
            }
        }
 
        public static async Task<HttpResult> HttpSendAsync(this IHttpClientFactory httpClientFactory,HttpMethod method,string url,string parameters = null,Dictionary<string, string> headers = null)
        {
            if (httpClientFactory == null)
                throw new ArgumentNullException(nameof(httpClientFactory));
            if (method == null)
                throw new ArgumentNullException(nameof(method));
            if (string.IsNullOrEmpty(url))
                throw new ArgumentNullException(nameof(url));
 
            var client = httpClientFactory.CreateClient();
            string finalUrl = url;
            HttpContent content = new StringContent("");
 
            try
            {
                // GET 拼接参数
                if (method == HttpMethod.Get && !string.IsNullOrWhiteSpace(parameters))
                {
                    finalUrl = url.Contains("?") ? $"{url}&{parameters}" : $"{url}?{parameters}";
                }
 
                // POST 处理参数
                if (method == HttpMethod.Post && !string.IsNullOrWhiteSpace(parameters))
                {
                    content = new StringContent(parameters, Encoding.UTF8, "application/x-www-form-urlencoded");
                }
 
                var request = new HttpRequestMessage(method, finalUrl) { Content = content };
 
                // 请求头
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        if (!request.Headers.TryAddWithoutValidation(header.Key, header.Value))
                        {
                            content.Headers.TryAddWithoutValidation(header.Key, header.Value);
                        }
                    }
                }
 
                using (var response = await client.SendAsync(request))
                {
                    // 读取返回内容
                    string responseContent = await response.Content.ReadAsStringAsync();
 
                    return new HttpResult
                    {
                        IsSuccess = response.IsSuccessStatusCode, // 是否成功
                        StatusCode = (int)response.StatusCode,    // 状态码 200/404/500
                        Content = responseContent,                // 返回内容
                        ErrorMsg = response.IsSuccessStatusCode ? "" : $"HTTP请求失败,状态码:{(int)response.StatusCode}"
                    };
                }
            }
            catch (Exception ex)
            {
                // 网络异常、超时等
                return new HttpResult
                {
                    IsSuccess = false,
                    StatusCode = 0, // 网络异常状态码设为0
                    Content = "",
                    ErrorMsg = ex.Message
                };
            }
        }
        /// <summary>
        /// HTTP 请求统一返回模型
        /// </summary>
        public class HttpResult
        {
            /// <summary>
            /// 是否请求成功(200-299)
            /// </summary>
            public bool IsSuccess { get; set; }
 
            /// <summary>
            /// HTTP 状态码(数字:200,404,500)
            /// </summary>
            public int StatusCode { get; set; }
 
            /// <summary>
            /// 返回内容
            /// </summary>
            public string Content { get; set; }
 
            /// <summary>
            /// 错误信息
            /// </summary>
            public string ErrorMsg { get; set; }
        }
    }
}