我有一个包含Web应用程序和API应用程序的系统。 两个应用程序都使用相同的服务层。 (这是3层架构)。 我在Service层上组织SignalR并将其注册在Web App的Startup.cs文件中。
当我调用SendToHub()方法时,SignalR在Web应用程序上可以正常工作。但是,如果我通过API调用SendToHub()则什么也没发生。
我的期望是,当从API App发出SignalR时,应该收到WebApp的前端通知。
服务呼叫
public void SendSignal() {
hub_communication.SendToHub(clientId:"", incommingText:"")
}
从网络应用和API调用:
Service.SendSignal();
一些SignalR配置:
public class MainHub : Hub {
public void Register(string group)
{
var clients = GlobalHost.ConnectionManager.GetHubContext<MainHub>();
UnRegisterAll(group, null);
SignalRConnectionToGroupsMap.TryAddGroup(Context.ConnectionId, group);
Clients.Caller.groupAdded(group);
}
public void UnRegisterAll(string userID, string organizationID)
{
var rets = new List<string>();
SignalRConnectionToGroupsMap.TryRemoveAll(Context.ConnectionId, out rets);
var clients = GlobalHost.ConnectionManager.GetHubContext<MainHub>();
Clients.Caller.groupRemovedAll(userID);
}
}
public static class hub_communication
{
public static void SendToHub(string clientid, string incoming)
{
var clients = GlobalHost.ConnectionManager.GetHubContext<MainHub>();
clients.Clients.Group(clientid).receiveMessage(incoming);
}
}
public static class SignalRConnectionToGroupsMap
{
private static readonly ConcurrentDictionary<string, List<string>> Map = new ConcurrentDictionary<string, List<string>>();
public static bool TryAddGroup(string connectionId, string groupName)
{
if (!Map.TryGetValue(connectionId, out var groups))
{
return Map.TryAdd(connectionId, new List<string>() { groupName });
}
if (!groups.Contains(groupName))
{
groups.Add(groupName);
}
return true;
}
public static bool TryRemoveAll(string connectionId, out List<string> result)
{
return Map.TryRemove(connectionId, out result);
}
}
Startup.cs
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
...
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration();
map.RunSignalR(hubConfiguration);
});
}
}
答案 0 :(得分:0)
这里的问题是您的应用程序在不同的域上运行。 在Startup.cs文件中。如下配置SignalR:
app.Map("/signalr", map =>
{
// Setup the CORS middleware to run before SignalR.
// By default this will allow all origins. You can
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
// You can enable JSONP by uncommenting line below.
// JSONP requests are insecure but some older browsers (and some
// versions of IE) require JSONP to work cross domain
// EnableJSONP = true
};
// Run the SignalR pipeline. We're not using MapSignalR
// since this branch already runs under the "/signalr"
// path.
map.RunSignalR(hubConfiguration);
});