Sending requests from the client to the hub via Razor Page's.
##comment down is a solution
CodePudding user response:
I'm not sure if this is what you need but you can define a render section inside _Layout.cshtml
<body>
...
...
...
@RenderSection("Scripts", required: false)
</body>
Then inside your razor page add:
<div id="counter"></div>
@section Scripts {
<script defer src="/main.509cbdfefce2f16684e8.js"></script>
}
https://docs.microsoft.com/en-us/aspnet/core/mvc/views/layout?view=aspnetcore-6.0#sections
Edit:
In your Hub you can define a method that pushes the viewCountUpdate event to the clients.
public class DevHub : Hub
{
public async Task CountUpdate()
=> await Clients.All.SendAsync("viewCountUpdate", 66);
}
Then call it from typescript using
await connection.invoke("CountUpdate");
CodePudding user response:
Now, few hours later i am comming here to tell you how i find out of my problem.
I decide to leave TS and i decide to go along with JS.
This is simple explanation:
My Hub class:
public class MainHub : Hub<IMainHub>
{
public static int ViewCount { get; set; } = 0;
//FROM HUB TO CLIENT
public async override Task OnConnectedAsync()
{
ViewCount ;
await Clients.All.ViewCountUpdate(ViewCount);
await base.OnConnectedAsync();
}
public async override Task OnDisconnectedAsync(Exception exception)
{
ViewCount--;
await Clients.All.ViewCountUpdate(ViewCount);
await base.OnDisconnectedAsync(exception);
}
My Hub Interface:
public interface IMainHub
{
Task ViewCountUpdate(int viewCount);
}
Razor Index.cshtml:
<h1>Watching connection list</h1>
<p>People watching this page: <span id="viewCounter">0</span></p>
@section Scripts{
<script src="~/lib/signalr/signalr.js"></script>
<script src="~/index.js"></script>
}
My index.js
const connection = new signalR.HubConnectionBuilder()
.withUrl("/testhub")
.configureLogging(signalR.LogLevel.Trace)
.withAutomaticReconnect([0, 10, 30, 60, 90, 150])
.build();
async function start() {
try {
await connection.start();
console.log("SignalR Connected.");
} catch (err) {
console.log(err);
setTimeout(start, 5000);
}
};
connection.onclose(async () => {
await start();
});
//FROM HUB TO CLIENT [EVENTS]
connection.on("ViewCountUpdate", (viewCount) => {
counter.innerHTML = viewCount;
});
// Start the connection.
start();
And now i can add reference to js scripts in everysingle page and it works.