Search code examples
asp.net-mvcasp.net-core-mvcsignalrsignalr.client

Message Does not Send from server To client in SignalR Asp.net core Web application


When i send message from server to client client doesn't Show the Message

This is my Program.cs file there i register Hub

using SignalR.Hubs;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSignalR();

builder.Services.AddControllersWithViews();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
  app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapHub<NotificationHub>("/notificationHub");

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

This is My Server controller

  public class ServerController : Controller
    {
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Index(Notification modal)
        {
            return View();
        }
    }

This is JS File

"use strict";

var connection = new signalR.HubConnectionBuilder()
    .withUrl("/notificationHub")
    .build();
connection.start();
console.log(connection);
connection.on("ReceiveMsg", function (msg) {
    alert('message')
    console.log('message ',msg)
    var li = document.createElement("li");
    li.textContent = msg;
    document.getElementById("msgList").appendChild(li);
})

This is my Client Side Html

<h1>Client App</h1>

<div id="servermsg">
    <ul id="msgList">
   

    </ul>
</div>
<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script src="~/js/ClientNotification.js"></script>

This is my Hub File.

When i debug the my Hub file when do not redirect when i send Message

public class NotificationHub:Hub
    {
        public async Task SendMessage(string message)
        {
            await Clients.All.SendAsync("ReceiveMsg", message);
        }
    }

I update and added Program.cs File in question


Solution

  • Since you are using the SignalR client (JavaScript) you will be easily able to send a message from the client too. The workflow is something like this:

    JavaScript Client

    1. Setup hubs and map them in the Program.cs (which you have done correctly)
    2. Add the events to listen in the hub (In your case you did it correctly in the NotificationHub using the SendMessage method)
    3. Add the SignalR client library and connect to the hub
    4. Create the form in the view and attach an event listener (using JavaScript) when click submit
    5. If have validated the previous step and you are sure it is safe to send the message call invoke method in the signalR.HubConnectionBuilder

    Here is a working example of what I meant in the previous list: JavaScript (Client):

    "use strict";
    
    //This is your code which is working fine
    var connection = new signalR.HubConnectionBuilder()
        .withUrl("/notificationHub")
        .build();
    
    connection.start();
    console.log(connection);
    
    connection.on("ReceiveMsg", function (msg) {
        alert('message')
        console.log('message ', msg);
        var li = document.createElement("li");
        li.textContent = msg;
        document.getElementById("msgList").appendChild(li);
    });
    
    //New code
    
    //Event listener attached to the submit button
    document.querySelector("#form-submit-btn").addEventListener("click", () => {
    
        //This needs to be called if the message is validated
        //You can run this conditionally based on the logic you wanna implement
        connection.invoke("SendMessage", document.querySelector("#message-input").value);
    });
    

    View

    <h1>Client App</h1>
    
    <div id="servermsg">
        <ul id="msgList">
       
    
        </ul>
    </div>
    
    <input type="text" id="message-input" />
    
    <button id="form-submit-btn" class="btn btn-primary">Send</button>
    

    .NET Client

    That is said for JavaScript client. The procedure is the same for .NET clients

    1. Install Microsoft.AspNetCore.SignalR.Client package from Nuget Package manager
    2. Configure the dependency injection with the type of HubConnection
    3. Start the connection in the constructor
    4. Call the InvokeAsync method in your action

    Here is the sample code of the Controller:

    private readonly HubConnection _hubConnection;
    
    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
        _hubConnection = new HubConnectionBuilder()
            .WithUrl("https://localhost:7159/notificationHub")
            .Build();
    
        _hubConnection.StartAsync();
    }
    
    [HttpPost]
    public async Task MessageHandler(string message)
    {
        await _hubConnection.InvokeAsync<string>("SendMessage", message);
    }
    

    View

    <div id="servermsg">
        <ul id="msgList">
       
    
        </ul>
    </div>
    
    <form asp-action="MessageHandler">
        <input type="text" name="message" id="message-input" />
    
        <button id="form-submit-btn" class="btn btn-primary">Send</button>
    </form>
    

    Microsoft Docs for invoke method (JS): Call hub methods from JavaScript client

    Microsoft Docs for invoke method (.NET C#): Call hub methods from .NET client