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

我有一个带有 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在集线器外部注入?


梦里花落0921
浏览 171回答 1
1回答

波斯汪

当调用构造函数时,上下文尚不可用。它将在调用预期函数时填充。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);     }   }
打开App,查看更多内容
随时随地看视频慕课网APP