I have first time implemented signalR concept and its working when page load first time and when I perform any insert, delete or updated operation on the database it calls a method which is specified in code but I am getting the null value of Context.User.Identity.Name. I have used FormAuthentication and after logged in I am getting connectionId and username but after make changes on a table of database getting the null value of username. Below I have mentioned my code.
我第一次实现了signalR概念及其在页面加载第一次时的工作,当我对数据库执行任何插入,删除或更新操作时,它调用了一个在代码中指定的方法,但我得到了Context.User的空值。 Identity.Name。我已经使用了FormAuthentication并且在登录后我得到了connectionId和username但是在对数据库表进行更改后获取了username的null值。下面我提到了我的代码。
HubClass
namespace SCPLTabAssessPortal
{
public class User
{
public string Name { get; set; }
public HashSet<string> ConnectionIds { get; set; }
}
[Authorize]
public class DashboardNewHub : Hub
{
int totalNewMessages = 0;
int ttltdy = 0;
int Ttlnum = 0;
int totalNewNotification = 0;
private static readonly ConcurrentDictionary<string, User> Users = new ConcurrentDictionary<string, User>();
public override Task OnConnected()
{
string userName = Context.User.Identity.Name;
string connectionId = Context.ConnectionId;
var user = Users.GetOrAdd(userName, _ => new User
{
Name = userName,
ConnectionIds = new HashSet<string>()
});
lock (user.ConnectionIds)
{
user.ConnectionIds.Add(connectionId);
Clients.AllExcept(user.ConnectionIds.ToArray()).userConnected(userName);
// TODO: Broadcast the connected user
}
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
string name = Context.User.Identity.Name;
User rmuser;
Users.TryRemove(name, out rmuser);
return base.OnDisconnected(stopCalled);
}
public override Task OnReconnected()
{
string name = Context.User.Identity.Name;
string connectionId = Context.ConnectionId;
var user = Users.GetOrAdd(name, _ => new User
{
Name = name,
ConnectionIds = new HashSet<string>()
});
lock (user.ConnectionIds)
{
user.ConnectionIds.Add(connectionId);
Clients.AllExcept(user.ConnectionIds.ToArray()).userConnected(name);
// TODO: Broadcast the connected user
}
return base.OnReconnected();
}
[HubMethodName("sendNotifications")]
public string SendNotifications()
{
IEnumerable<string> allReceivers = null;
try
{
User getuser = GetUser(Context.User.Identity.Name);
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SCPLDBPortalConnectionString"].ConnectionString))
{
string query = "SELECT [ColumnName],[ColumnName] FROM [dbo].[TableName] ";
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
try
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
int totaltax = 0;
foreach (DataRow r in dt.Rows)
{
totaltax += (string.IsNullOrEmpty(Convert.ToString(r["TaxTotal"])) ? 0 : Convert.ToInt32(r["TaxTotal"]));
}
totalNewMessages = totaltax;
}
connection.Close();
}
catch (Exception ex)
{
throw;
}
}
}
User receiver;
if (Users.TryGetValue(getuser.Name, out receiver))
{
User sender = GetUser(Context.User.Identity.Name);
lock (receiver.ConnectionIds)
{
lock (sender.ConnectionIds)
{
allReceivers = receiver.ConnectionIds.Concat(sender.ConnectionIds);
}
}
foreach (var cid in allReceivers)
{
Clients.Client(cid).received(totalNewMessages);
}
}
}
catch (Exception ex) {
}
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<DashboardNewHub>();
return (string)context.Clients.Client(Convert.ToString(allReceivers.Last())).RecieveNotification(totalNewMessages).Result;
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
DashboardNewHub nHub = new DashboardNewHub();
nHub.SendNotifications();
}
}
private User GetUser(string username)
{
User user;
Users.TryGetValue(username, out user);
return user;
}
}
}
JqueryCode
jQuery(document).ready(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.dashboardNewHub;
// Create a function that the hub can call to broadcast messages.
notifications.client.recieveNotification = function (totalNewMessages, ttltdy) {
$('#TtlColl').text(totalNewMessages);
};
// Start the connection.
$.connection.hub.start().done(function () {
notifications.server.sendNotifications();
}).fail(function (e) {
alert(e);
});
});
Global.asax.cs
protected void Application_Start(object sender, EventArgs e)
{
SqlDependency.Start(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
}
protected void Application_End(object sender, EventArgs e)
{
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
}
Login.cs
The below code I wrote while a user is logging in.
我在用户登录时编写的以下代码。
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, true);
FormsAuthentication.SetAuthCookie(txtUserName.Text + "$" + DS.Tables[0].Rows[i]["ID"].ToString(), true);
1 个解决方案
#1
0
The point is because is the sql broker engine to call nHub.SendNotifications()
you can't get any informations about the user logged-in as is not the user logged is making the request
关键是因为sql代理引擎调用nHub.SendNotifications()你无法获得有关登录用户的任何信息,因为记录的用户不是在发出请求
#1
0
The point is because is the sql broker engine to call nHub.SendNotifications()
you can't get any informations about the user logged-in as is not the user logged is making the request
关键是因为sql代理引擎调用nHub.SendNotifications()你无法获得有关登录用户的任何信息,因为记录的用户不是在发出请求