Я пытаюсь понять, как HttpContext.Current.User.Identity работает с Signal Hub.
Я запускаю сигнализатор, используя словарь, чтобы сохранить все userNames и ваши connectionsIds
Мое приложение работает нормально при первом запуске, однако через несколько секунд оно ломается. Это снова выдает ошибку об HttpContext.Current.User.Identity.
Возвращено значение null я.
Вот ошибка, которую я получил:
![enter image description here](https://i.stack.imgur.com/SNV0Q.png)
Вот мой код: [ChatHub]
namespace SistemaJaspion.AppCode
{
[HubName("chatHub")]
[Authorize]
public class ContadorHub : Hub
{
private readonly static ConnectionMapping<string> _connections = new ConnectionMapping<string>();
string userLogged = new Usuario().ReturnUserId(Convert.ToInt32(HttpContext.Current.User.Identity.Name)).Nome;
public void SendChatMessage(string who, string message)
{
string name = new Usuario().ReturnUserId(Convert.ToInt32(HttpContext.Current.User.Identity.Name)).Nome;
foreach (var connectionId in _connections.GetConnections(who))
{
Clients.Client(connectionId).addChatMessage(name + ": " + message);
}
}
public override Task OnConnected()
{
string name = userLogged;
//string name = new Usuario().ReturnUserId(Convert.ToInt32(HttpContext.Current.User.Identity.Name)).Nome;
_connections.Add(name, Context.ConnectionId);
//foreach (KeyValuePair<string, string> entry in _connections)
//{
// // do something with entry.Value or entry.Key
//}
// Update the number of the connected users
int totalIndice = _connections.Count;
Clients.All.reportConnections(_connections.Count);
string quantidade = "";
quantidade = _connections.GetAllConnections().ToString();
//foreach (var in _connections)
//{
// Debug.Write(value.ToString());
//}
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
string name = userLogged;
//string name = new Usuario().ReturnUserId(Convert.ToInt32(HttpContext.Current.User.Identity.Name)).Nome;
_connections.Remove(name, Context.ConnectionId);
return base.OnDisconnected(stopCalled);
}
public override Task OnReconnected()
{
string name = userLogged;
//string name = new Usuario().ReturnUserId(Convert.ToInt32(HttpContext.Current.User.Identity.Name)).Nome;
if (!_connections.GetConnections(name).Contains(Context.ConnectionId))
{
_connections.Add(name, Context.ConnectionId);
}
return base.OnReconnected();
}
}
//Testing
public class ConnectionMapping<T>
{
private readonly Dictionary<T, HashSet<string>> _connections = new Dictionary<T, HashSet<string>>();
public int Count
{
get
{
return _connections.Count;
}
}
public void Add(T key, string connectionId)
{
lock (_connections)
{
HashSet<string> connections;
if (!_connections.TryGetValue(key, out connections))
{
connections = new HashSet<string>();
_connections.Add(key, connections);
}
lock (connections)
{
connections.Add(connectionId);
}
}
}
public string UserNameHiddenField(string UserName)
{
return UserName;
}
public int GetAllConnections()
{
int quantity = 0;
lock (_connections)
{
foreach (KeyValuePair<T, HashSet<string>> comp in _connections)
{
quantity++;
}
Debug.Write(quantity);
}
return quantity;
}
//Obtém conexões de um dedeterminado usuário
public IEnumerable<string> GetConnections(T key)
{
HashSet<string> connections;
if (_connections.TryGetValue(key, out connections))
{
return connections;
}
return Enumerable.Empty<string>();
}
public void Remove(T key, string connectionId)
{
lock (_connections)
{
HashSet<string> connections;
if (!_connections.TryGetValue(key, out connections))
{
return;
}
lock (connections)
{
connections.Remove(connectionId);
if (connections.Count == 0)
{
_connections.Remove(key);
}
}
}
}
}
}
Мой webConfig:
<authentication mode="Forms">
<forms loginUrl="~/p/Login.aspx" defaultUrl="~/p/TarefasProcessos.aspx" protection="All" timeout="600" name=".ASPXFORMSAUTH" path="/" requireSSL="false" slidingExpiration="true" enableCrossAppRedirects="false" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
Каков наилучший способ получения HttpContext.Current.User.Identity внутри chatHub?