This commit is contained in:
yxw
2025-12-04 19:07:04 +08:00
parent 6217a8ca55
commit bd95848972
13 changed files with 484 additions and 127 deletions

View File

@@ -2,14 +2,26 @@
using Atomx.Utils.Json;
using System.Net.Http.Json;
using System.Text;
using Microsoft.AspNetCore.Http;
namespace Atomx.Admin.Client.Services
{
public class HttpService(HttpClient httpClient)
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)
{
var response = await httpClient.GetAsync(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();
@@ -24,8 +36,13 @@ namespace Atomx.Admin.Client.Services
public async Task<T> Post<T>(string url, object data)
{
var json = data.ToJson();
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(url, content);
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();
@@ -46,7 +63,14 @@ namespace Atomx.Admin.Client.Services
page = 1;
}
url = $"{url}?page={page}&size={size}";
var response = await httpClient.PostAsJsonAsync(url, data);
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();
@@ -54,6 +78,7 @@ namespace Atomx.Admin.Client.Services
}
else
{
// 明确抛 Unauthorized 以便上层按需处理
throw new Exception($"Error: {response.StatusCode}");
}
}
@@ -63,5 +88,32 @@ namespace Atomx.Admin.Client.Services
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
{
// 忽略任何转发异常,保持健壮性
}
}
}
}