c# - 如何使用signalR核心从asp.net核心接收消息到UWP
问题描述
SignalR 核心是使用 javascript 客户端或 Angular 进行演示的我的案例是使用 UWP 来呈现前端。虽然微软只告诉如何从客户端调用消息到服务器,但它的文档没有显示如何接收消息 [ https://docs.microsoft.com/en-us/aspnet/core/signalr/dotnet-client?view =aspnetcore-2.2][1]
这是我的服务器:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSingleton<IInventoryServices, InventoryServices>();
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseSignalR(route =>
{
route.MapHub<MessageHub>("/hub");
});
app.UseMvc();
}
}
这是控制器:
[Route("api/hub")]
[ApiController]
public class MessController : Controller
{
private IHubContext<MessageHub> _messhubContext;
public MessController(IHubContext<MessageHub> messhubContext)
{
_messhubContext = messhubContext;
}
public ActionResult Post()
{
_messhubContext.Clients.All.SendAsync("send", "Strypper", "Howdy");
System.Diagnostics.Debug.WriteLine("I'm here");
return Ok();
}
这里是集线器:
public class MessageHub : Hub
{
public Task Send(string user ,string message)
{
return Clients.All.SendAsync("Send", user, message);
}
}
我的“邮递员”搞砸了,我不想讨论它。这里有没有人使用 uwp 框架可以向我展示从我制作的服务器接收消息的方式?
解决方案
不好意思,原来是我理解错了,转过来了。
对于服务器到客户端的通信,您必须遵循此处的文档。
你需要像这样在 UWP 中定义一个监听器:
connection.On<string, string>("ReceiveMessage", (user, message) =>
{
//do something
});
并像这样在服务器端发送消息:
await Clients.All.SendAsync("ReceiveMessage", user,message);
上一个答案
要从客户端调用Hub
方法,您可以使用该InvokeAsync
方法:
await connection.InvokeAsync("MyMethod", "someparameter");
然后你只需在Hub
类中创建方法
public class MessageHub : Hub
{
public Task Send(string user ,string message)
{
return Clients.All.SendAsync("Send", user, message);
}
public Task MyMethod(string parameter)
{
//do something here
}
}
还有一个重载InvokeAsync<TResult>
允许您创建具有返回类型的方法。
推荐阅读
- python - 为什么这个程序总是返回 326 作为 d 的值
- javascript - 发送带有 MultipartFile 字段的对象列表返回 415 Unsupported Media Type
- python - Python 从单词列表中获取所有可能性来创建段落
- python - 如何在字典中存储列表中的多个值
- google-sheets - 如何在 Google 表格的分数数据库中找到最佳分数?
- flutter - Cloud Firestore 在流中等待未来 - 使用用户 ID 将用户加入文档
- ios - 从锁定的 iOS 设备接听 VoIP 电话后直接打开 iOS (Flutter) 应用程序
- c - 为什么子进程使用execlp在父进程之后执行?
- python - 从字典列表中获取特定值并将该值用作嵌套字典列表中的新键
- python - 关于合并值的奇怪重复,字典中的键