使用Signalr(1.0.0-alpha2),我想知道在连接启动后是否可以添加客户端功能.
假设我创建了我的连接并获取代理.然后我将一些Server Fired客户端功能添加到集线器中以执行一些操作.然后我开始我的连接.然后我想在我的hub对象中添加一些Server Fired函数.这可能吗?
var myHub= $.connection.myHub;
myHub.SomeClientFunction = function() {
alert("serverside called 'Clients.SomeClientFunction()'");
};
$.connection.hub.start()
.done(function() {
myHub.SomeNewClientFunction = function() {
alert("serverside called 'Clients.SomeNewClientFunction()'");
}
})
Run Code Online (Sandbox Code Playgroud)
这个例子不太现实,但我基本上想在集线器开始订阅原始代码不关心的新事件后,将我的'myHub'变量发送到另一个对象.
真实生活示例:包含许多不同中心事件的仪表板(新站点访问,聊天消息,站点错误).我在连接开始后"订阅",然后将我的集线器代理传递给我所有不同的UI组件,以处理他们特定的"消息类型".我应该为这些创建单独的集线器还是应该能够动态添加更多服务器触发的客户端功能?
我的解决方案中有两个项目:
项目1:"SignalRChat"(MVC) - 工作正常
项目2:"DatabaseWatcherService"Windows服务 - 正常工作
我正试图从我的Windows服务中调用SignalRChat Hub,但它似乎没有工作.
这是我通过Windows服务调用我的Hub的地方(https://github.com/SignalR/SignalR/wiki/Hubs#broadcasting-over-a-hub-from-outside-of-a-hub):
void PerformTimerOperation(object sender, EventArgs e)
{
eventLog1.WriteEntry("Timer ticked...");
var message = "test";
var context = GlobalHost.ConnectionManager.GetHubContext<SignalRChat.ChatHub>();
context.Clients.All.addNewMessageToPage(message);
}
Run Code Online (Sandbox Code Playgroud)
尝试连接时出现以下错误:
消息=远程服务器返回错误:(500)内部服务器错误.
我正在尝试通过连接 var connection = new HubConnection("http://localhost:2129");
端口2129是我运行的MVC项目.
我想我错过了一些非常简单的事情,也许只需要一套新的眼睛.我有一个ASP.NET MVC应用程序.在那个应用程序中,我使用Unity来处理IoC来处理依赖注入.我的每个存储库都需要注入一个数据库工厂,每个数据库工厂都需要注入一个主体.到目前为止,我一直在使用PerRequestLifetimeManager来注册这些.
//Repositories
container.RegisterType<ChatMessageRepository>(new PerRequestLifetimeManager());
container.RegisterType<SignalRConnectionRepository>(new PerRequestLifetimeManager());
//Context
container.RegisterType<IPrincipal, Principal>(new PerRequestLifetimeManager());
container.RegisterType<IDatabaseFactory, DatabaseFactory>(new PerRequestLifetimeManager());
container.RegisterType<UnitOfWork>(new PerRequestLifetimeManager());
Run Code Online (Sandbox Code Playgroud)
从逻辑上讲,我试图以同样的方式注册我的Hub.
container.RegisterType<ChatHub>(new PerRequestLifetimeManager());
Run Code Online (Sandbox Code Playgroud)
但是,每当我运行我的应用程序并离开我的聊天页面时,我得到"依赖失败的解决方案"异常,而InnerException告诉我"由于对象的当前状态,操作无效".我也尝试使用默认(Transient),PerResolve和ContainerControlled生命周期Unity管理员注册这些人,似乎无法解决我的问题.
有人可以给我一些演示代码,说明如何在ASP.NET MVC应用程序中使用Unity来处理信号器集线器中的依赖注入?
这是Unity将参数注入SignalR Hub的地方
public class ChatHub : Hub
{
private readonly ChatMessageRepository _chatMessageRepository;
private readonly SignalRConnectionRepository _signalRConnectionRepository;
private readonly UnitOfWork _unitOfWork;
public ChatHub(ChatMessageRepository chatMessageRepository,
SignalRConnectionRepository signalRConnectionRepository,
UnitOfWork unitOfWork)
{
_chatMessageRepository = chatMessageRepository;
_signalRConnectionRepository = signalRConnectionRepository;
_unitOfWork = unitOfWork;
} ... }
Run Code Online (Sandbox Code Playgroud)
谢谢!
dependency-injection ioc-container unity-container signalr signalr-hub
我很难决定如何最好地为我的SignalR服务添加身份验证和授权.
目前,它与WebApi2 Web服务一起托管在Owin中.我使用OAuth2持有者令牌来验证这些令牌,并且它完美无缺.但是,我想知道它们是否适合SignalR?
我的客户端是基于JavaScript的,SignalR使用WebSockets(如果可用).这意味着我无法使用Authorization标头.我发现在连接之前我可以使用qs属性提供令牌.但是,OAuth2访问令牌当然会过期(在我的实现中相对较短).我假设更新qs属性一旦连接(特别是与Web套接字),将不会有所作为.
我想我的问题是什么是向SignalR提供安全令牌,票证或任何类型的授权信息的最佳方式?最好是一种可以在我的WebApi和SignalR上保持一致的方式,但我想知道我应该怎么做.
谢谢
我创建了一个SignalR集线器,它包含以下集线器功能:
public bool GetStatus()
{
return true;
}
Run Code Online (Sandbox Code Playgroud)
我想从我的JS代码中调用此函数并获取此调用的请求.像这样的东西:
var result = hub.server.getStatus();
if (result)
alert('success');
Run Code Online (Sandbox Code Playgroud)
这可能没有返回bool的任务吗?
谢谢.
服务器端:
public override Task OnConnected()
{
var connectionId = Context.ConnectionId;
var user = Context.User.Identity.Name; // Context.User is NULL
return base.OnConnected();
}
Run Code Online (Sandbox Code Playgroud)
客户端(在Console项目中):
IHubProxy _hub;
string url = @"http://localhost:8080/";
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("TestHub");
connection.Start().Wait();
Run Code Online (Sandbox Code Playgroud)
当客户端连接到服务器时,我想知道userName和connectionId之间的映射,但是Context.User为NULL。如何在客户端设置此值?
我想在SignalR请求的生命周期内静态存储用户信息.我在WebAPI中使用HttpContext.Current.Items这样做但在SignalR中不存在.
我知道ThreadStatic不会工作,因为SignalR线程可以在多个请求之间共享.
作为参考,我在IIS中托管它并使用最新版本的SignalR(2.2.0)
我有一个 web api 控制器,我想在其中使用事件处理程序。更具体地说,我有一个MessagesController,当执行 action 方法时,WriteMessage我想触发一个SignalR Hub method将订阅a 的事件,该方法将向所有必要的接收者广播消息。看看下面的简化代码:
这是控制器:
public class MessagesController : ApiController
{
private readonly IMessageService _messageService;
public EventHandler<MessageEventArgs> MessageSent;
public MessagesController(IMessageService messageService)
{
_messageService = messageService;
}
public IHttpActionResult WriteMessage(Message message)
{
try
{
//here I'm using MessageService to write the message to the data base
_messageService.WriteMessage(message);
//after the message was saved successfully I would like to trigger the event that will fire a signalR hub's method
OnMessageSent(message);
return Content(HttpStatusCode.Created, …Run Code Online (Sandbox Code Playgroud) 上下文:ASP.NET SignalR和ASP.NET Core SignalR之间有区别,您可以在此处阅读。
如本ASP.NET SignalR中的stackoverflow文章所述,您可以通过HubPipelineModuleASP.NET Core SignalR中不存在的异常在服务器端捕获未处理的异常。
我们如何捕获未处理的异常并将其传递给ASP.NET Core SignalR中的客户端?
JavaScript代码(客户端):
var hub = null;
var initWebSocket = function () {
hub = new signalR.HubConnectionBuilder().withUrl("/MyHub").build();
hub.on("ReceiveMessage", function (pMessage) {
[...]
});
hub.start().catch(function (err) {
return console.error(err.toString());
});
};
var executeWebsocketTestException = function () {
// send to server
hub.invoke("TestException").catch(function (exception) {
if(exception.type)
{
...
}
});
};
Run Code Online (Sandbox Code Playgroud)
ASP.NET Core 2集线器(服务器):
public class MyHub : Hub
{
public async Task TestException()
{
throw new …Run Code Online (Sandbox Code Playgroud) 在 Angular 6 中使用 SignalR 做一个非常简单的调用来设置连接/停止,我有以下代码:
信号R.helper.ts
public static setupHub<T>(hubUrl: string, eventName: string, callback: (data: T) => void, ...params: SignalRParam[]): HubConnection {
const token = localStorage.getItem(appConstant.token);
const url = this.buidlUrl(hubUrl, ...params);
const connection = new HubConnectionBuilder()
.withUrl(url,
{ transport: HttpTransportType.WebSockets, accessTokenFactory: () => token })
.build();
environment.production && connection.start();
!environment.production && connection.start().catch(err => console.error(err.toString()));
connection.on(eventName, callback);
return connection;
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试在我的页面上登录,我会在控制台上不断收到此错误:
signalR.helper.ts:19 错误:如果连接未处于“已连接”状态,则无法发送数据。
我是 SignalR 和 Angular 的新手,为什么我一直收到这个错误?
signalr ×10
signalr-hub ×10
c# ×4
asp.net ×2
.net ×1
angular ×1
angular6 ×1
controller ×1
javascript ×1
typescript ×1