亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 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 關注
  • 209 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號