为请求记录创建唯一字符串ASP.NET Core MVC



我有一个请求表,它需要为用户显示一个唯一的字符串Id。

经过一些搜索,我发现凯文的帖子非常适合我。此处

但是,当请求的id开始为4位(例如5041(时,我得到了一个IndexOutOfRangeException错误。这怎么可能?我该怎么修?

private static Random random = new Random();
private static int largeCoprimeNumber = 502277;
private static int largestPossibleValue = 1679616;
private static char[] Base36Alphabet = new char[] { '0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' };
public static string GetTicket(int id)
{
int adjustedID = id * largeCoprimeNumber % largestPossibleValue;
string ticket = IntToString(adjustedID);
while (ticket.Length < 4)  
ticket = "0" + ticket;
return ticket + new string(Enumerable.Repeat(Base36Alphabet, 6).Select(s => s[random.Next(s.Length)]).ToArray());
}
private static string IntToString(int value)
{
string result = string.Empty;
int targetBase = Base36Alphabet.Length;
do
{
result = Base36Alphabet[value % targetBase] + result;
value = value / targetBase;
}
while (value > 0);
return result;
}

调用GetTicket方法:

Request request = new Request()
{
//properties
};
_db.Request.Add(request);
await _db.SaveChangesAsync();
request.TicketId = GetTicket(request.Id);

答案是:当你相乘时,答案大于整数Max,这会导致数字为负数。解决方案是将类型更改为long。

这里是测试代码:

private static Random random = new Random();
private static long largeCoprimeNumber = 502277;
private static long largestPossibleValue = 1679616;
private static char[] Base36Alphabet = new char[] { '0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' };
public static string GetTicket(long id)
{
long adjustedID = (id * largeCoprimeNumber) % largestPossibleValue;
string ticket = LongToString(adjustedID);
while (ticket.Length < 4) ticket = "0" + ticket;
return ticket + new string(Enumerable.Repeat(Base36Alphabet, 6).Select(s => s[random.Next(s.Length)]).ToArray());
}
private static string IntToString(int value)
{
string result = string.Empty;
int targetBase = Base36Alphabet.Length;
do
{
result = Base36Alphabet[value % targetBase] + result;
value = value / targetBase;
}
while (value > 0);
return result;
}
private static string LongToString(long value)
{
string result = string.Empty;
int targetBase = Base36Alphabet.Length;
do
{
result = Base36Alphabet[value % targetBase] + result;
value = value / targetBase;
}
while (value > 0);
return result;
}

最新更新