127 lines
5.6 KiB
C#
127 lines
5.6 KiB
C#
using Microsoft.AspNetCore.Http;
|
||
using Microsoft.AspNetCore.Mvc;
|
||
using Microsoft.Extensions.DependencyInjection;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Net.Http.Headers;
|
||
using System.Net;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
using System.Security.Policy;
|
||
using System.Text.Json;
|
||
using Learn.Archives.Core.Model.Dto;
|
||
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||
|
||
namespace Learn.Archives.Core.Common
|
||
{
|
||
public static class UserCenterServiceExpand
|
||
{
|
||
|
||
/// <summary>
|
||
/// 添加 当前作用域登录用户信息
|
||
/// </summary>
|
||
/// <param name="services"></param>
|
||
public static void AddUserCenterServiceExpand(this IServiceCollection services)
|
||
{
|
||
services.AddScoped<UserCenterService>();
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 调用 UserCenter服务的接口
|
||
/// </summary>
|
||
public class UserCenterService
|
||
{
|
||
private readonly IHttpClientFactory _httpClientFactory;
|
||
|
||
public UserCenterService(IHttpClientFactory httpClientFactory)
|
||
{
|
||
_httpClientFactory = httpClientFactory;
|
||
}
|
||
|
||
const string API_getpageuserlist = "back/users/getpageuserlist";
|
||
const string API_ImportJsonData = "back/users/importjsondata";
|
||
/// <summary>
|
||
/// 请求用户中心 接口
|
||
/// </summary>
|
||
/// <param name="context"></param>
|
||
/// <returns></returns>
|
||
public async Task<PageResult<UserInfoResponceDto>> CallAPI_GetPageUserList(HttpContext context)
|
||
{
|
||
var res = await ForwardRequestAsync<BaseReturn<PageResult<UserInfoResponceDto>>>(API_getpageuserlist, context);
|
||
if (res==null || res.Code != 200)
|
||
Oh.Error(res.Message, res.Code);
|
||
return res.Data;
|
||
}
|
||
/// <summary>
|
||
/// 请求用户中心 接口
|
||
/// </summary>
|
||
/// <param name="context"></param>
|
||
/// <returns></returns>
|
||
public async Task<UserImportRes> CallAPI_ImportJsonData(HttpContext context,object data)
|
||
{
|
||
|
||
var httpClient = _httpClientFactory.CreateClient();
|
||
|
||
var targetUri = new Uri(AppCommon.Config.UserCenterService.API +"/"+ API_ImportJsonData);
|
||
var requestMessage = new HttpRequestMessage(new HttpMethod("POST"), targetUri);
|
||
|
||
if (context.Request.Headers.TryGetValue("Authorization", out var authValues))
|
||
requestMessage.Headers.Authorization = AuthenticationHeaderValue.Parse(authValues.FirstOrDefault());
|
||
requestMessage.Content = new StringContent(data.ToJson(), Encoding.UTF8, "application/json");
|
||
|
||
var responseMessage = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead);
|
||
var resStr = await responseMessage.Content?.ReadAsStringAsync();
|
||
var res = JsonSerializer.Deserialize<BaseReturn<UserImportRes>>(resStr);
|
||
if (res == null || res.Code != 200)
|
||
Oh.Error(res.Message, res.Code);
|
||
return res.Data;
|
||
}
|
||
/// <summary>
|
||
/// 转发请求
|
||
/// </summary>
|
||
/// <param name="url">用户中心API</param>
|
||
/// <param name="context">上下文</param>
|
||
/// <returns></returns>
|
||
public async Task<T> ForwardRequestAsync<T>(string url, HttpContext context) where T : class, new()
|
||
{
|
||
var httpClient = _httpClientFactory.CreateClient();
|
||
var Request = context.Request;
|
||
try
|
||
{
|
||
// ========== 1. 准备目标请求 ==========
|
||
var targetUri = new Uri(AppCommon.Config.UserCenterService.API+"/"+ url);
|
||
|
||
// 创建 HttpRequestMessage,使用与当前请求相同的 HttpMethod
|
||
var requestMessage = new HttpRequestMessage(new HttpMethod(Request.Method), targetUri);
|
||
|
||
// ========== 2. 复制请求头 ==========
|
||
// ========== 3. 处理请求体(Body)==========
|
||
if (Request.Body != null && (Request.Method == "POST" || Request.Method == "PUT" || Request.Method == "PATCH"))
|
||
{
|
||
// 由于 Request.Body 只能读取一次,我们需要缓存它(ASP.NET Core 默认不缓存)
|
||
// 如果你希望多次读取 Body,可以使用 EnableBuffering() 中间件,或者在这里直接读取并重新赋值
|
||
Request.EnableBuffering(); // 允许重新读取请求流
|
||
Request.Body.Position = 0; // 重置 Stream 位置,以便后续中间件或框架再次读取(如有必要)
|
||
using var reader = new System.IO.StreamReader(Request.Body);
|
||
var body = await reader.ReadToEndAsync();
|
||
if (!string.IsNullOrEmpty(body))
|
||
requestMessage.Content = new StringContent(body, Encoding.UTF8, Request.ContentType);
|
||
}
|
||
// ========== 4. 添加 Authorization 等自定义 Header(可选)==========
|
||
if (Request.Headers.TryGetValue("Authorization", out var authValues))
|
||
requestMessage.Headers.Authorization = AuthenticationHeaderValue.Parse(authValues.FirstOrDefault());
|
||
// ========== 5. 发送请求到目标服务器 ==========
|
||
var responseMessage = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead);
|
||
var resStr = await responseMessage.Content?.ReadAsStringAsync();
|
||
return JsonSerializer.Deserialize<T>(resStr);
|
||
}
|
||
catch
|
||
{
|
||
throw;
|
||
}
|
||
}
|
||
|
||
}
|
||
}
|