为了账号安全,请及时绑定邮箱和手机立即绑定

在 SignalR Core 中访问或注入 Hub 外部的 HubCallerContext

在 SignalR Core 中访问或注入 Hub 外部的 HubCallerContext

C#
梦里花落0921 2023-07-22 18:31:50
我有一个带有 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 回答

?
波斯汪

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); 

    }   

}


查看完整回答
反对 回复 2023-07-22
  • 1 回答
  • 0 关注
  • 170 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信