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 Get(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(); } else { throw new Exception($"Error: {response.StatusCode}"); } } public async Task Post(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(); } else { throw new Exception($"Error: {response.StatusCode}"); } } public async Task>> GetPagingList(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>>(); } else { // 明确抛 Unauthorized 以便上层按需处理 throw new Exception($"Error: {response.StatusCode}"); } } catch (HttpRequestException ex) { Console.WriteLine(ex.ToString()); throw new Exception($"api {url} service failure"); } } /// /// 如果在 Server 环境并且 IHttpContextAccessor 可用,则把浏览器请求的 Cookie 转发到后端请求中 /// 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 { // 忽略任何转发异常,保持健壮性 } } } }