Files
QYZH.InteractiveMagazine/QYZH.InteractiveMagazine.Common/Helpers/RandomIdHelper.cs
glz 88e5fd23be refactor(common&service): adjust id range and remove unused qr code method
1. 调整RandomIdHelper的默认ID生成范围从16位改为13位
2. 从IUserJournalService和UserJournalService中移除废弃的单例生成二维码方法
3. 为相关DTO添加JSON数字序列化/反序列化配置,处理前后端数字类型兼容问题
4. 修改二维码内容序列化逻辑,将数字转为字符串避免精度丢失
2026-07-02 16:16:24 +08:00

38 lines
1.1 KiB
C#

using System.Security.Cryptography;
namespace QYZH.InteractiveMagazine.Common.Helpers;
/// <summary>
/// 随机ID帮助类
/// </summary>
public static class RandomIdHelper
{
private const long DefaultMinValue = 1_000_000_000_000L;
private const long DefaultMaxValue = 9_000_000_000_000_000L;
/// <summary>
/// 生成不可预测的正数长整型ID
/// </summary>
public static long GenerateLongId(long minValue = DefaultMinValue, long maxValue = DefaultMaxValue)
{
if (minValue <= 0 || minValue >= maxValue)
{
throw new ArgumentOutOfRangeException(nameof(minValue), "随机ID范围配置错误");
}
var range = (ulong)(maxValue - minValue);
var limit = ulong.MaxValue - (ulong.MaxValue % range);
Span<byte> bytes = stackalloc byte[sizeof(ulong)];
while (true)
{
RandomNumberGenerator.Fill(bytes);
var value = BitConverter.ToUInt64(bytes);
if (value < limit)
{
return minValue + (long)(value % range);
}
}
}
}