【问题标题】:How to receive message from the asp.net core using signalR core to UWP如何使用signalR核心从asp.net核心接收消息到UWP
【发布时间】:2018-12-08 10:42:39
【问题描述】:

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 框架可以告诉我从我制作的服务器接收消息的方式?

【问题讨论】:

    标签: c# uwp asp.net-core-signalr


    【解决方案1】:

    对不起,我原来是误会了,转过来了。

    对于服务器到客户端的通信,您必须遵循documentation here

    你需要像这样在 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&lt;TResult&gt; 的重载,允许您创建具有返回类型的方法。

    【讨论】:

      猜你喜欢
      • 2019-07-19
      • 2017-05-20
      • 1970-01-01
      • 2018-09-21
      • 2019-08-18
      • 1970-01-01
      • 2017-10-23
      • 2019-06-30
      相关资源
      最近更新 更多