我第一次实现了signalR概念及其在第一次加载页面时的工作情况,当我对数据库执行任何插入,删除或更新操作时,它调用了一个在代码中指定的方法,但我得到了Context的null值.User.Identity.Name。我已经使用了FormAuthentication,登录后我得到了connectionId和用户名,但是在对数据库表进行更改后获取了username的空值。下面我提到了我的代码。
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;
}
}
}
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);
});
});
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);
}
我在用户登录时编写的以下代码。
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, true);
FormsAuthentication.SetAuthCookie(txtUserName.Text + "$" + DS.Tables[0].Rows[i]["ID"].ToString(), true);
答案 0 :(得分:0)
关键是因为调用nHub.SendNotifications()
的sql代理引擎无法获得有关登录用户的任何信息,因为记录的用户不是在发出请求