![](/img/trans.png)
[英]Access SignalR Hub Context.Items from an singleton service in ASP.NET Core
[英]SignalR ASP.Net Core offers no way to Add Context Items via Typescript Client
我正在打開從Typescript客戶端到C#SignalR集線器的連接。 似乎沒有辦法添加上下文項。
客戶:
public startConnection(hubRoute: string): void {
const fixedRoute = `${this._baseUrl}${hubRoute}`;
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(fixedRoute)
.build();
this.hubConnection
.start()
.then(() => console.log('Connection started'))
.catch(err => console.log('Error while starting connection: ' + err));
/// where and how to add context items here?
}
服務器:
public class EditorialHub: Hub<IEditorialHub>
{
public override async Task OnConnectedAsync()
{
if (Context.Items["IssueNumber"] is string issueNumber)
{
await Groups.AddToGroupAsync(Context.ConnectionId, "IssueNumber_" + issueNumber);
}
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception exception)
{
if (Context.Items["IssueNumber"] is string issueNumber)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, "IssueNumber_" + issueNumber);
}
await base.OnDisconnectedAsync(exception);
}
}
我可以從客戶端添加“ IssueNumber” Context.Item嗎?
您可以像這樣將數據從客戶端發送到SignalR集線器
public async Task Send(string userId)
{
var message = $"Send message to you with user id {userId}";
await Clients.Client(userId).SendAsync("ReceiveMessage", message);
}
public string GetConnectionId()
{
return Context.ConnectionId;
}
我定義了2種方法1,用於將消息從服務器發送到客戶端名稱Send,以及1種方法,將消息從客戶端發送到服務器
並在js代碼中
import * as signalR from "@aspnet/signalr";
const connection = new signalR.HubConnectionBuilder()
.withUrl("/hub")
.build();
connection.start().then(function () {
console.log("connected");
connection.invoke('getConnectionId')
.then(function (connectionId) {
sessionStorage.setItem('conectionId', connectionId);
// Send the connectionId to controller
}).catch(err => console.error(err.toString()));;
});
$("#sendmessage").click(function () {
var connectionId = sessionStorage.getItem('conectionId');
connection.invoke("Send", connectionId);
});
connection.on("ReceiveMessage", function (message) {
console.log(message);
});
connection.invoke('getConnectionId')
將是從客戶端向服務器發送數據的方法
和connection.on("ReceiveMessage"
將是接收從客戶端發送到服務器的消息的消息
我這樣做是這樣,盡管在任何地方的文檔中都找不到。 如果是復雜的對象,則可以將所需的任何集合傳遞到值中(只需指定要放置字符串值的類型)。
public void SetContextItems(string key, string value)
{
Context.Items.Add(key, value);
}
這是針對服務器端*。 對於客戶端,您可以像@Tony Ngo一樣調用此方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.