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; }
|
}
|
}
|
}
|