I am trying to implement live notifications in my web application. Only the users which are administrators in my web app should see the notifications.
So I setup the web socket in my startup.cs file which I think is not the right way
Startup.cs
var webSocketOptions = new WebSocketOptions()
{
KeepAliveInterval = TimeSpan.FromSeconds(120),
ReceiveBufferSize = 4 * 1024
};
app.UseWebSockets(webSocketOptions);
app.Use(async (context, next) =>
{
if (context.Request.Path == "/ws")
{
if (context.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}
});
and this is my Javascript
window.onload = () => {
if (/*User is Admin*/) {
//Establish Websocket
var socket = new WebSocket("wss:localhost:44301/ws");
console.log(socket.readyState);
socket.onerror = function (error) {
console.log('WebSocket Error: ' + error);
};
socket.onopen = function (event) {
console.log("Socket connection opened")
};
// Handle messages sent by the server.
socket.onmessage = function (event) {
var data = event.data;
console.log(data);
//Draw some beautiful HTML notification
};
}
}
now this all works, but I don't know how to send messages from my server controllers, something like this
[HttpGet]
public async Task<IActionResult> Foo(WebSocket webSocket)
{
//What I am trying to do is send message from the open web socket connection.
var buffer = new byte[1024 * 4];
buffer = Encoding.UTF8.GetBytes("Foo");
await webSocket.SendAsync(new ArraySegment<byte>(buffer),WebSocketMessageType.Text,true,CancellationToken.None);
return View()
}
I don't know how to approach this. What I wanna do is if the user is admin, open web socket and send some data from the other users actions, (which means writing messages from that opened web socket from some of my controllers)