首页 文章

如何使用signalR核心从UWP接收来自asp.net核心的消息

提问于
浏览
0

SignalR核心是使用javascript客户端或Angular进行演示我的情况是使用UWP渲染前端 . 虽然Microsoft只告诉如何从客户端调用消息到服务器,但是's docs didn' t显示了如何接收消息[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);
    }
}

我的“PostMan”搞砸了,我不想讨论它 . 有没有人在这里使用uwp框架可以告诉我从我做的服务器接收消息的方式?

1 回答

  • 0

    对不起,我原本误解了并转过身来 .

    对于服务器到客户端的通信,您必须遵循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<TResult> 的重载,允许您创建具有返回类型的方法 .

相关问题