Biraj Dahal
Biraj Dahal

Reputation: 57

How Can I send Clients value in ASP.NET Controller?

I have written a code in c#, javascript, using client library SignalR to refresh a page in database value change. My code is

<form asp-action="Start" method="post" class="form-stacked">
    <button type="submit" id="startPractice" class="button-primary">Start Practice</button>
</form>

<script src="~/js/ignalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>

My API method is which is called while clicking start practice is

public async Task<IActionResult> Index(long sessionId)
{
     // Database change logic

     SignalRClientHub sr = new SignalRClientHub();
     await sr.SendMessage();

     // Rest of the logic

     return this.View();
}

 public class SignalRClientHub : Hub
    {
        public async Task SendMessage(string user = null, string message = null)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }

code of chat.js

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/SignalRClient").build();

connection.on("ReceiveMessage", function (user, message) {
    location.reload();
});

When I click the button start practice it hits SendMessage Method, but I got an error

object reference not set to an instance

because the value of the Client was null. How Can I fix this?

Upvotes: 0

Views: 98

Answers (1)

Brennan
Brennan

Reputation: 1931

You cannot new up a hub manually. In order to send to clients from outside of the hub you need to use the IHubContext<THub>. See the docs for details https://learn.microsoft.com/aspnet/core/signalr/hubcontext?view=aspnetcore-5.0

Upvotes: 1

Related Questions