A:初版提交

This commit is contained in:
jimmy committed 2025-11-13 18:14:51 +08:00
1 parent c9778a3e7c
commit 43ff9bc57f
21 files changed
+1655

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Common.Utils;
public static class JsonHelper
{
public static readonly JsonSerializerOptions CamelCaseOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
Converters =
{
new IpAddressConverter(), new JsonStringEnumConverter(JsonNamingPolicy.CamelCase, allowIntegerValues: false)
},
};
public static string ToJson<T>(T value) =>
JsonSerializer.Serialize(value, CamelCaseOptions);
public static T? FromJson<T>(string json) =>
JsonSerializer.Deserialize<T>(json, CamelCaseOptions);
}
/*
IPAddress.ScopeId 属性在某些情况下(如 IPv4 类型)是不被支持的,会抛出异常。
这是 .NET 的设计问题,访问 ScopeId 只有在 IPv6 地址中才有意义,在 IPv4 中访问它就会抛出这个 10045 错误。
*/
public class IpAddressConverter : JsonConverter<IPAddress>
{
public override IPAddress Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var ipString = reader.GetString() ?? String.Empty;
return IPAddress.Parse(ipString);
}
public override void Write(Utf8JsonWriter writer, IPAddress value, JsonSerializerOptions options)
{
writer.WriteStringValue(value?.ToString());
}
}
+44
View File
@@ -0,0 +1,44 @@
using System.Net;
using System.Net.Sockets;
namespace Common.Utils;
public static class SystemHelper
{
/// <summary>
/// 获取可用端口
/// </summary>
/// <returns></returns>
public static int GetAvailablePort()
{
// todo: 2025/6/24 15:53 开发过程中使用固定端口
// return 8267;
TcpListener listener = new TcpListener(IPAddress.Loopback, 0); // 端口号为0表示由系统自动分配
listener.Start();
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
/// <summary>
/// 检查当前进程是否以管理员权限运行
/// </summary>
/// <returns>如果是管理员权限返回 true,否则返回 false</returns>
/// <exception cref="PlatformNotSupportedException">仅支持 Windows 平台</exception>
/// <remarks>
/// 此方法仅适用于 Windows 操作系统。
/// 在非 Windows 平台上会抛出 PlatformNotSupportedException 异常。
/// </remarks>
public static bool IsAdministrator()
{
if (!OperatingSystem.IsWindows())
{
throw new PlatformNotSupportedException("IsAdministrator method is only supported on Windows platform.");
}
var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
var principal = new System.Security.Principal.WindowsPrincipal(identity);
return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
}
}