[英]AbpSession always return null when start using Websocket
I'm using asp.net boilerplate framework, and I'm trying to set the WebSocket connection to become match the logged-in user id when the user establishes the WebSocket connection, but what I noticed is the AbpSession.UserId value is always null, so這是什么原因,雖然在其他類中它工作正常,這是我的代碼:
public class WebSocketServerConnectionManager : ITransientDependency
{
private ConcurrentDictionary<string, WebSocket> _socket = new ConcurrentDictionary<string, WebSocket>();
public IAbpSession AbpSession { get; set; }
public WebSocketServerConnectionManager()
{
AbpSession = NullAbpSession.Instance;
}
public ConcurrentDictionary<string, WebSocket> GetAllSockets()
{
return _socket;
}
public string AddSocket(WebSocket socket)
{
try
{
var ConnId = AbpSession.UserId.ToString(); //<==== Null
// Guid.NewGuid().ToString();
//var test = AbpSession.UserId;
_socket.TryAdd(ConnId/*dictionary item key*/, socket/*dictionary item value*/);
Debug.WriteLine("Connection Added:" + ConnId);
return ConnId;
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
}
更新:
這是客戶端 WebSocket 初始化:
async ngOnInit() {
this.connectWebSocket();
}
connectWebSocket(){
this.socket=new WebSocket(this.webSocketUrl);
this.socket.onopen=(event)=>{
}
this.socket.onclose=(event)=>{
}
this.socket.onmessage=(event)=>{
this.isConnID(event.data);
}
}
您需要傳遞身份驗證信息。
如果您使用的是 ASP.NET 樣板 Angular 模板(帶有模塊零),您可以在查詢字符串中傳遞enc_auth_token
,這將由QueryStringTokenResolver
解析。
// import { AppConsts } from '@shared/AppConsts';
// import { UtilsService } from 'abp-ng2-module';
connectWebSocket(){
// this.socket=new WebSocket(this.webSocketUrl); // Change this to the following
const encryptedAuthToken = new UtilsService().getCookieValue(AppConsts.authorization.encryptedAuthTokenName);
const webSocketUrl = this.webSocketUrl + '?enc_auth_token=' + encodeURIComponent(encryptedAuthToken);
this.socket = new WebSocket(webSocketUrl);
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.