吴晓阳
发布于 2025-03-17 / 15 阅读
0

Admin.NET添加开放接口

using Admin.NET.Plugin.Wms.Option;

namespace Admin.NET.Plugin.HrRcs;


public class RemoteFilterHandler : DelegatingHandler, ITransient
{
    // 这里支持构造函数依赖注入
    private readonly SysOpenAccessService _openAccess = App.GetService<SysOpenAccessService>();

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        var param = new GenerateSignatureInput()
        {
            AccessKey = App.GetOptions<OpenAPIOptions>().Api_Key,
            AccessSecret = App.GetOptions<OpenAPIOptions>().Api_Secret,
            Method = HttpMethodEnum.Post,
            Url = request.RequestUri.LocalPath,
            Timestamp = Convert.ToInt64(ts.TotalSeconds),
            Nonce = new Random().Next(100000, 999999).ToString(),
        };
        request.AppendHeaders(new Dictionary<string, object> {
            { "accessKey", param.AccessKey},
            { "timestamp", param.Timestamp},
            { "nonce", param.Nonce},
            { "sign", _openAccess.GenerateSignature(param)}
        });
        return await base.SendAsync(request, cancellationToken);
    }
}

    public void ConfigureServices(IServiceCollection services)
    {
        services.TryAddTransient<RemoteFilterHandler>();
        services.AddHttpClient(name: "RemoteClient", configureClient: x =>
        {
            x.BaseAddress = new Uri($"https://np.wxy.work/");
            x.DefaultRequestHeaders.Add(name: "User-Agent", value: "HttpClient-wxy");
        }).AddHttpMessageHandler<RemoteFilterHandler>();
    }
    [HttpGet("helloWord")]
    [AllowAnonymous]
    public async Task<object> HelloWord()
    {
        var data = new { page = 1, pageSize = 10,total = 0 };
        var json = JsonConvert.SerializeObject(data);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        var client = _httpClientFactory.CreateClient("RemoteClient");
        var response = await client.PostAsync("https://np.wxy.work/prod-api/api/banji/page", content);
        var str = await response.Content.ReadAsStringAsync();

        // 使用 Newtonsoft.Json 解析 JSON 响应
        var obj = JsonConvert.DeserializeObject<AdminNETResult<SqlSugarPagedList<BanjiOutput>>>(str);
        return obj;
        //return Task.FromResult($"Hello, {_userManager.Account}.");
    }