Files
Atomx/Atomx.Admin/Atomx.Admin.Client/Services/HttpService.cs
2025-12-04 19:07:04 +08:00

120 lines
4.1 KiB
C#

using Atomx.Common.Models;
using Atomx.Utils.Json;
using System.Net.Http.Json;
using System.Text;
using Microsoft.AspNetCore.Http;
namespace Atomx.Admin.Client.Services
{
public class HttpService
{
private readonly HttpClient _httpClient;
private readonly IHttpContextAccessor? _httpContextAccessor;
public HttpService(HttpClient httpClient, IHttpContextAccessor? httpContextAccessor = null)
{
_httpClient = httpClient;
_httpContextAccessor = httpContextAccessor;
}
public async Task<T> Get<T>(string url)
{
using var request = new HttpRequestMessage(HttpMethod.Get, url);
AttachCookieIfServer(request);
var response = await _httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return content.FromJson<T>();
}
else
{
throw new Exception($"Error: {response.StatusCode}");
}
}
public async Task<T> Post<T>(string url, object data)
{
var json = data.ToJson();
using var request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
AttachCookieIfServer(request);
var response = await _httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
return responseContent.FromJson<T>();
}
else
{
throw new Exception($"Error: {response.StatusCode}");
}
}
public async Task<ApiResult<PagingList<T>>> GetPagingList<T>(string url, object data, int page, int size = 20)
{
try
{
if (page < 1)
{
page = 1;
}
url = $"{url}?page={page}&size={size}";
using var request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = JsonContent.Create(data)
};
AttachCookieIfServer(request);
var response = await _httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return content.FromJson<ApiResult<PagingList<T>>>();
}
else
{
// 明确抛 Unauthorized 以便上层按需处理
throw new Exception($"Error: {response.StatusCode}");
}
}
catch (HttpRequestException ex)
{
Console.WriteLine(ex.ToString());
throw new Exception($"api {url} service failure");
}
}
/// <summary>
/// 如果在 Server 环境并且 IHttpContextAccessor 可用,则把浏览器请求的 Cookie 转发到后端请求中
/// </summary>
private void AttachCookieIfServer(HttpRequestMessage request)
{
try
{
if (!OperatingSystem.IsBrowser())
{
var ctx = _httpContextAccessor?.HttpContext;
if (ctx != null && ctx.Request.Headers.TryGetValue("Cookie", out var cookie) && !string.IsNullOrEmpty(cookie))
{
// 覆盖或添加 Cookie header
if (request.Headers.Contains("Cookie"))
{
request.Headers.Remove("Cookie");
}
request.Headers.Add("Cookie", (string)cookie);
}
}
}
catch
{
// 忽略任何转发异常,保持健壮性
}
}
}
}