0
votes

My AspnetCore application does not receive publications from a .net core console application via SignalR

I have an aspnet core 2.1 web application that contains a SignalR Hub.

I need to make a .net core 2.1 console application that send information to my hub on my web system.

I did a development here, however when I run my console app, no exception appears, but my web application does not receive the information.

See what I've done so far.

Aspnet Core 2.1

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();
            services.AddSession();
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddSignalR();
            services.AddMvc(
                    config => {
                    var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                    config.Filters.Add(new AuthorizeFilter(policy));
                }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddAuthentication(options =>
            {
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
                options =>
                {
                    options.ExpireTimeSpan = TimeSpan.FromDays(1);
                    options.LoginPath = "/Home/Login";
                    options.LogoutPath = "/Usuario/Logout";
                    options.SlidingExpiration = true;
                });
            //provedor postgresql
            services.AddEntityFrameworkNpgsql()
             .AddDbContext<MesContext>(options => 
             options.UseNpgsql(Configuration.GetConnectionString("MesContext")));

            services.AddScoped<SeedingService>();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, SeedingService seedingService)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            seedingService.Seed();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseSession();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            
            app.UseSignalR(routes =>
            {
                routes.MapHub<MesHub>("/MesHub");
            });
        }
    }

View Index

//teste
    // ATUALIZA LISTAGEM
    connection.on("teste", function (sucesso, msg) {
        if (sucesso) {
            console.log(msg);
        }
    });

Hub

public class MesHub : Hub
    {
        public static ConcurrentDictionary<string, List<string>> ConnectedUsers = new ConcurrentDictionary<string, List<string>>();

        
        public void SendAsync(string message)
        {
            // Call the addMessage method on all clients
             Clients.All.SendAsync("teste", true, message);
        }

        public override Task OnConnectedAsync()
        {
            string name = Context.User.Identity.Name;

            Groups.AddToGroupAsync(Context.ConnectionId, name);

            return base.OnConnectedAsync();
        }
    }

Console aplication

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Teste Renan!");

            var url = "https://localhost:44323/meshub";

            var connection = new HubConnectionBuilder()
                .WithUrl($"{url}")
                .WithAutomaticReconnect() //I don't think this is totally required, but can't hurt either
                .Build();

            var t = connection.StartAsync();
            Console.WriteLine("conected!");
            //Wait for the connection to complete
            t.Wait();

            Console.WriteLine(connection.State);
            

            //connection.SendAsync("SendAsync", "renan");

            connection.InvokeAsync<string>("SendAsync", "HELLO World ").ContinueWith(task => {
                if (task.IsFaulted)
                {
                    Console.WriteLine("There was an error calling send: {0}",
                                      task.Exception.GetBaseException());
                }
                else
                {
                    Console.WriteLine(task.Result);
                }
            });
            Console.WriteLine("enviado!"); 
}
}

In the console app I add the Microsoft.aspnetCore.SignalR.Client package

Signalr works very well within the aspnet core web system, as it is not receiving information externally.

I'm forgetting something? what am I doing wrong?

1
If you debug the hub method, does it hit expected method while you invoke it from console client app? - Fei Han
Is not. So far I have found what is causing the problem, in my Hub I have an OnConnectedAsync method where the name of the group is informed, since no application console I am not setting the group and so it does not connect. - Renan
in my Hub I have an OnConnectedAsync method where the name of the group is informed Hi @Renan, please check my new updates. - Fei Han

1 Answers

2
votes

I define same hub method and do a test to invoke it from the console client, which work as expected.

Besides, I test it with my SignalR console client app, it works well too. If possible, you can test it and check if it works for you.

static void Main(string[] args)
{
    Console.WriteLine("Client App Starts...");

    Program p = new Program();
    p.Myfunc().Wait();

    Console.ReadLine();

}

public async Task Myfunc()
{
    HubConnection connection = new HubConnectionBuilder()
        .WithUrl("https://localhost:44323/meshub") 
        .Build();

    connection.Closed += async (error) =>
    {
        await Task.Delay(new Random().Next(0, 5) * 1000);
        await connection.StartAsync();
    };


    await connection.StartAsync();

    try
    {
        await connection.InvokeAsync("SendAsync", "HELLO World ");
        //await connection.InvokeAsync("SendMessage", "console app", "test mes");
    }
    catch (Exception ex)
    {

        Console.WriteLine(ex.Message);
    }
       
}

Test Result

enter image description here

Updated:

in my Hub I have an OnConnectedAsync method where the name of the group is informed

You can try to update the OnConnectedAsync method as below, then check if your SignalR console client app can connect to hub and communicate with web client well.

public override async Task OnConnectedAsync()
{
    string name = Context.User.Identity.Name;

    if (name != null)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, name);
    }

    await base.OnConnectedAsync();
}