I have written the following code to establish connection with signalR server and invoke a hub method:
<script>
var connection = new signalR.HubConnectionBuilder().withUrl("/signalRServer").withAutomaticReconnect().build();
connection.start().then( result => {
console.log("RealTime connection is now established")
});
function ShowMessageAndUpdate(messageId, data){
$('#messageModal').modal('show');
$('#mainTxt').text(data);
var formData2 = new FormData();
formData2.append("messageId", messageId);
$.ajax({
type: "POST",
url: "Messages/UpdateMessageStatus",
contentType: false,
processData: false,
data: formData2,
success: function (response) {
if (response.success) {
console.log("status changed successfully!");
var table2 = $('#table2').DataTable();
table2.ajax.reload();
connection.invoke("MessageUpdate", messageId).catch(function(err){
return console.error(err)
});
} else {
console.log("status change failed.");
}
},
error: function (error) {
console.log(error);
}
});
}
</script>
The hub method is invoked when the success response of jQuery is True
.
The problem is that console cannot establish a connection with the hub.
Messages:377 Error: Failed to invoke 'MessageUpdate' due to an error on the server. at H. (signalr.js:1:13973) at L.I (signalr.js:1:14804) at X.L.connection.onreceive (signalr.js:1:10649) at WebSocket.r.onmessage (signalr.js:1:27565)
Is there anything wrong with my client side code?
Update: method in the hub is as follows:
public async Task MessageUpdate(int messageId)
{
int destination = _messageRepository.GetSenderIdByMessageId(messageId);
string username = _userRepository.GetUserNameById(destination);
var userId = NtoIdMappingTable.GetValueOrDefault(username);
await Clients.User(userId.FirstOrDefault()).SendAsync("ReceiveMessageUpdate");
}
The problem is in client side, because method is not run when debugging. connection cannot be established correctly when it gets parameter from function(parameter)
.