刘磊
2025-04-19 bd02cb3fa0fa75ffafb2cf17501929b1b1e0029b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
 
 
namespace WIDESEAWCS_SignalR;
 
/// <summary>
/// 用户ID提供器
/// </summary>
public class UserIdProvider : IUserIdProvider
{
    public string GetUserId(HubConnectionContext connection)
    {
        var token = connection.GetHttpContext().Request.Query["access_token"];//获取token
        var userId = JwtHelper.GetUserId(token);//解析token
        if (userId > 0)//如果不为空
            return $"{userId}_{CreateLetterAndNumber(5)}";//返回用户ID
        else
            return connection.ConnectionId;
    }
 
    /// <summary>
    /// 生成随机字母和数字随机数
    /// </summary>
    /// <param name="Length">生成长度</param>
    /// <returns></returns>
    public static string CreateLetterAndNumber(int Length)
    {
        char[] array = new char[62]
        {
            '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', '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', '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9'
        };
        string text = "";
        int maxValue = array.Length;
        Random random = new Random((int)(~DateTime.Now.Ticks));
        for (int i = 0; i < Length; i++)
        {
            int num = random.Next(0, maxValue);
            text += array[num];
        }
 
        return text;
    }
}