Nic*_*une 5 signalr-hub asp.net-core
语境
我正在将 SignalR 3 RC1 与 ASP.NET 5 用于我的项目,但我无法让我的客户端订阅特定组,以从我的服务器接收消息。
枢纽类
[HubName("ChatHub")]
public class ChatHub : Hub
{
public async Task Join(string userId)
{
if (!string.IsNullOrEmpty(userId))
{
await Groups.Add(Context.ConnectionId, userId);
}
}
}
Run Code Online (Sandbox Code Playgroud)
JS代码
var chatHub = hubConnection.createHubProxy("chatHub");
chatHub .on("newMessage", (response) => {
console.log(response);
});
hubConnection.start().done(response => {
chatHub.invoke("join", "userid");
});
Run Code Online (Sandbox Code Playgroud)
网络接口
public class ChatController : ApiController
{
protected readonly IHubContext ChatHub;
public ChatController(IConnectionManager signalRConnectionManager)
{
ChatHub = signalRConnectionManager.GetHubContext<ChatHub>();
}
[Authorize]
[HttpPost]
[Route("Message")]
public async Task<IActionResult> CreateMessage([FromBody] messageParams dto)
{
await ChatHub.Clients.Group("userid").NewMessage("hello world");
}
}
Run Code Online (Sandbox Code Playgroud)
如果我广播“所有”客户端,它就可以工作。
await ChatHub.Clients.All.NewMessage("hello world");
Run Code Online (Sandbox Code Playgroud)
是否有特定的配置来向特定组广播消息?
对于有兴趣将 ASP.NET 5 与 Signalr 2.2 一起使用的人,我在 IAppBuilder 和 IApplicationBuilder 之间创建了一座桥梁
internal static class IApplicationBuilderExtensions
{
public static void UseOwin(
this IApplicationBuilder app,
Action<IAppBuilder> owinConfiguration)
{
app.UseOwin(
addToPipeline =>
{
addToPipeline(
next =>
{
var builder = new AppBuilder();
owinConfiguration(builder);
builder.Run(ctx => next(ctx.Environment));
Func<IDictionary<string, object>, Task> appFunc =
(Func<IDictionary<string, object>, Task>)
builder.Build(typeof(Func<IDictionary<string, object>, Task>));
return appFunc;
});
});
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseOwin(owin => owin.MapSignalR());
}
Run Code Online (Sandbox Code Playgroud)
导入这些依赖项
"Microsoft.AspNet.Owin": "1.0.0-rc1-final",
"Microsoft.Owin": "3.0.1"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1208 次 |
| 最近记录: |