Azure SignalR Service
An Azure service that is used for adding real-time communications to web applications.
151 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I'm having error 401 Unauthorized with this code:
using Microsoft.AspNetCore.SignalR.Client;
using System.Collections.ObjectModel;
namespace ChatSignalAir;
public partial class MainPage : ContentPage
{
private readonly HubConnection _hubConnection;
private readonly ObservableCollection<string> _messages = new ObservableCollection<string>();
public MainPage()
{
InitializeComponent();
MessagesListView.ItemsSource = _messages;
_hubConnection = new HubConnectionBuilder()
.WithUrl("https://saservice.service.signalr.net/client/?hub=chat", options =>
{
options.AccessTokenProvider = () => Task.FromResult("mykey");
// Ignore certificate verification
options.HttpMessageHandlerFactory = messageHandler =>
{
var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => true // Ignores verification errors
};
return handler;
};
})
.Build();
_hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
MainThread.BeginInvokeOnMainThread(() => _messages.Add($"{user}: {message}"))
);
ConnectToHubAsync();
}
private async void ConnectToHubAsync()
{
try
{
await _hubConnection.StartAsync();
}
catch (HttpRequestException httpEx)
{
// Here you can capture error details
await DisplayAlert("Error", $"Failed to connect: {httpEx.StatusCode} - {httpEx.Message}", "OK");
}
catch (Exception ex)
{
await DisplayAlert("Error", $"Unexpected error: {ex.Message}", "OK");
}
}
private async void OnSendClicked(object sender, EventArgs e)
{
if (_hubConnection.State != HubConnectionState.Connected)
{
await DisplayAlert("Error", "Connection to SignalR is not active.", "OK");
return;
}
var message = MessageEntry.Text?.Trim();
if (string.IsNullOrEmpty(message))
{
await DisplayAlert("Warning", "Message cannot be empty.", "OK");
return;
}
try
{
await _hubConnection.InvokeAsync("SendMessage", "User", message); // Adjust as necessary
MessageEntry.Text = string.Empty;
}
catch (Exception ex)
{
await DisplayAlert("Error", $"Error sending message: {ex.Message}", "OK");
}
}
}
I doubt that "mkey" is a valid jwt access token. your code need to get a valid access token (which are normally good for about 20 minutes). for Maui you would typically use the msal library to get the token.