using System.Diagnostics; using System.Net; using System.Text.Json; namespace XFEExtension.NetCore.ServerInteractive.Utilities.Helpers; /// /// 服务器交互帮助类 /// public static class InteractiveHelper { private static readonly HttpClient s_client = new(); /// /// 获取响应 /// /// 请求地址 /// 请求体 /// public static async Task<(string, HttpStatusCode)> GetServerResponse(string requestAddress, string postBody) { var result = await s_client.PostAsync(requestAddress, new StringContent(postBody)); try { return (await result.Content.ReadAsStringAsync(), result.StatusCode); } catch (Exception ex) { return (ex.Message, result.StatusCode); } } /// /// 获取响应 /// /// 请求地址 /// 请求体对象 /// 序列化参数 /// public static async Task<(string, HttpStatusCode)> GetServerResponse(string requestAddress, object postBody, JsonSerializerOptions jsonSerializerOptions) => await GetServerResponse(requestAddress, JsonSerializer.Serialize(postBody, jsonSerializerOptions)); /// /// 获取Stopwatch的时间字符串 /// /// /// public static string GetStopWatchTime(Stopwatch stopwatch) { if (stopwatch.Elapsed.TotalSeconds > 1) { return $"{stopwatch.Elapsed.TotalSeconds:F1} s"; } if (stopwatch.Elapsed.TotalMilliseconds > 1) { return $"{stopwatch.Elapsed.TotalMilliseconds:F1} ms"; } return stopwatch.Elapsed.TotalMicroseconds > 1 ? $"{stopwatch.Elapsed.TotalMicroseconds:F1} μs" : $"{stopwatch.Elapsed.TotalNanoseconds:F1} ns"; } }