我有一个带有 signalR 实现的 asp-net-core 项目。我需要Context.User在我的中心调用方法时提取用户信息。问题是,当正在构建的集线器Context.User不包含用户信息时。但在方法范围内,Context.User正是我所期望的。public class Basehub : Hub{ public Basehub(IUserProfileProvide userProfileProvider) { this.CurrentUser = userProfileProvider.InitUserProfile(Context); // Context.User is empty when breakpoint hits this line } public IUserProfile CurrentUser {get;}}public class NotificationHub: BaseHub{private IUserProfileProvide userProfileProvider; public NotificationHub(IUserProfileProvide userProfileProvider) { } public async Task InvokeMe(string message) { var contextUser = Context.User; var profile = CurrentUser;//this is empty because Context is empty in the construction phase await Clients.All.SendAsync("invoked",message); // Context.User is OK when breakpoint hits this line } }我的主要目标是注入HubCallerCOntext并IUserProfileProvide尽可能BaseHub干净。*我的问题:如何HubCallerContext在集线器外部注入?
1 回答
![?](http://img1.sycdn.imooc.com/533e51f30001edf702000200-100-100.jpg)
波斯汪
TA贡献1811条经验 获得超4个赞
当调用构造函数时,上下文尚不可用。
它将在调用预期函数时填充。
public class Basehub : Hub {
protected IUserProfileProvide userProfileProvider;
public Basehub(IUserProfileProvide userProfileProvider) {
this.userProfileProvider = userProfileProvider;
}
}
在流程中推迟对它的访问,就像在框架有时间正确填充上下文时的方法中一样。
public class NotificationHub: BaseHub {
public NotificationHub(IUserProfileProvide userProfileProvider)
: base(userProfileProvider) { }
public async Task InvokeMe(string message) {
IUserProfile profile = userProfileProvider.InitUserProfile(Context); //context populated
//...
await Clients.All.SendAsync("invoked",message);
}
}
- 1 回答
- 0 关注
- 170 浏览
添加回答
举报
0/150
提交
取消