CloudGamingAdmin/admin-server/CloudGaming.Core.AgileConfig/AgileConfigServer.cs
2024-11-15 02:58:48 +08:00

106 lines
3.0 KiB
C#

using CloudGaming.Core.AgileConfig.AgileConfigApi;
using HZY.Framework.DependencyInjection;
using Quartz.Impl.Triggers;
using Refit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace CloudGaming.Core.AgileConfig;
public class AgileConfigServer
{
//public AgileConfigServer(IHttpClientFactory? httpClientFactory)
//{
// _httpClientFactory = httpClientFactory;
//}
public AgileConfigVM AgileConfig;
/// <summary>
/// 获取数据
/// </summary>
public IAgileConfigApi? AgileConfigApi { get; set; }
public IHttpClientFactory? _httpClientFactory { get; set; }
/// <summary>
/// token
/// </summary>
public string Token { get; set; }
/// <summary>
///
/// </summary>
public DateTime ExAt { get; set; }
public async Task Init(AgileConfigVM agileConfigVM)
{
AgileConfig = agileConfigVM;
//ExAt = DateTime.Now;
var isLogin = await LoginAsync();
if (!isLogin)
{
throw new InvalidOperationException("初始化失败");
}
var handler = new AuthenticatedHttpClientHandler(Token);
}
public async Task<bool> LoginAsync()
{
using var client = _httpClientFactory.CreateClient();
client.BaseAddress = new Uri(AgileConfig.Url);
var AuthClient = RestService.For<IAuthClient>(client);
var loginRequest = new LoginRequest { UserName = AgileConfig.UserName, Password = AgileConfig.Password };
var loginResponse = await AuthClient?.LoginAsync(loginRequest);
if (loginResponse != null && !string.IsNullOrEmpty(loginResponse.Token))
{
this.Token = loginResponse.Token;
ExAt = DateTime.Now.AddHours(6);
//var httpClient = httpClientFactory.CreateClient();
var httpClient = new HttpClient(new AuthenticatedHttpClientHandler(loginResponse.Token))
{
BaseAddress = new Uri("http://124.220.55.158:94")
};
AgileConfigApi = RestService.For<IAgileConfigApi>(httpClient);
return true;
}
return false;
}
public async Task Test4()
{
// 调用登录接口获取 JWT 令牌
var authClient = RestService.For<IAuthClient>("http://124.220.55.158:94");
var loginRequest = new LoginRequest { UserName = "admin", Password = "dbt@com@1234" };
var loginResponse = await authClient.LoginAsync(loginRequest);
string jwtToken = loginResponse.Token;
// 使用 JWT 令牌调用受保护的 API
var httpClient = new HttpClient(new AuthenticatedHttpClientHandler(jwtToken))
{
BaseAddress = new Uri("http://124.220.55.158:94")
};
try
{
var agileConfigClient = RestService.For<IAgileConfigApi>(httpClient);
var model = await agileConfigClient.GetJson("CloudGaming", "DEV");
}
catch (Exception ex)
{
}
}
}