【问题标题】:SignalR GetHubContext by nameSignalR GetHubContext 按名称
【发布时间】:2021-01-29 02:07:36
【问题描述】:

我想改变这个:

var context = GlobalHost.ConnectionManager.GetHubContext<ControlHub>(); 
context.Clients.All.sentMessage(room, username, message);

使用变量作为调用的一部分进行类似的操作;

var variableHere = "<ControlHub>";
var context = GlobalHost.ConnectionManager.GetHubContext(variableHere)(); 
context.Clients.All.sentMessage(room, username, message);

我很难把它放在一起。我认为反思或委托工作流程会让我到达那里,但在采用任何一种工作方式时都陷入了困境。

我试图弄清楚如何将变量作为方法/函数调用的一部分插入。在 C# 中(特别是 MVC 框架)

感谢任何建议或帮助。

【问题讨论】:

  • 你们把我带到了那里!谢谢。只需要更多的脑细胞(由他人捐赠)即可完成解决方案。这就是魔法:var context = GlobalHost.ConnectionManager.GetHubContext(hubString);
  • 我重新打开了这个问题,因为建议的副本不是解决这个问题的合适方法。
  • @HongDongDang:var context = GlobalHost.ConnectionManager.GetHubContext(typeof(ControlHub).Name); 。有用吗?

标签: c# .net signalr


【解决方案1】:

这里不需要反思。 ConnectionManager.GetHubContext 有另一个重载,它接受集线器名称作为参数。

您的代码可以像这样使用其他重载:

string hubName = "the hub name";
var context = GlobalHost.ConnectionManager.GetHubContext(hubName);

以防万一您想根据类型提取集线器名称,请查看 SignalR source code 内部的操作方式。如果您需要类似的功能,请将以下 GetHubName 扩展方法更改为公共扩展方法并使用它:

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. 
// See License.txt in the project root for license information.

using System;

namespace Microsoft.AspNet.SignalR.Hubs
{
    internal static class HubTypeExtensions
    {
        internal static string GetHubName(this Type type)
        {
            if (!typeof(IHub).IsAssignableFrom(type))
            {
                return null;
            }

            return GetHubAttributeName(type) ?? GetHubTypeName(type);
        }

        internal static string GetHubAttributeName(this Type type)
        {
            if (!typeof(IHub).IsAssignableFrom(type))
            {
                return null;
            }

            // We can still return null if there is no attribute name
            return ReflectionHelper
             .GetAttributeValue<HubNameAttribute, string>(type, attr => attr.HubName);
        }

        private static string GetHubTypeName(Type type)
        {
            var lastIndexOfBacktick = type.Name.LastIndexOf('`');
            if (lastIndexOfBacktick == -1)
            {
                return type.Name;
            }
            else
            {
                return type.Name.Substring(0, lastIndexOfBacktick);
            }
        }
    }
} 

【讨论】: