i have a websocket client and server and i'm trying to add a certificate to my client, but i don't think i have the hang of it yet..
i have an asp.net core 7 web api and wonder what i do wrong
Client:
public async Task<string> GetEcho(string echoMessageKey, string echoMessageValue)
{
X509Certificate2 certificate = new X509Certificate2("certPath", "password");
_clientWebSocket.Options.ClientCertificates.Add(certificate);
//connect to server
var xferURI = new Uri(uri);
await _clientWebSocket.ConnectAsync(xferURI, CancellationToken.None);
var messageInEcho = new Dictionary<string, string>
{
{ echoMessageKey,echoMessageValue }
};
//specify command
var echoCommand = new
{
echo = messageInEcho
};
return await ReceiveMessage(echoCommand);
}
public async Task<string> ReceiveMessage(object? Command)
{
var commandJSON = Encoding.UTF8.GetBytes
(JsonConvert.SerializeObject(Command));
await _clientWebSocket.SendAsync(new ArraySegment<byte>(commandJSON)
, WebSocketMessageType.Text, true, CancellationToken.None);
// receive and process the websocket message
var buffer = new byte[1024 * 60];//new byte[1024];
var result = await _clientWebSocket.ReceiveAsync(new ArraySegment<byte>(buffer),
CancellationToken.None);
var message = Encoding.UTF8.GetString(buffer, 0, result.Count);
// close connect to websocket
await _clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure,
"", CancellationToken.None);
return message;
}
[HttpGet("GetEcho")]
[ActionName(nameof(GetEcho))]
public async Task<IActionResult> GetEcho(string echoMessageKey, string echoMessageValue)
{
try
{
var echo = await _yunexXFER.GetEcho(echoMessageKey, echoMessageValue);
return Ok(echo);
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
Server:
var wsOptions = new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(120) };
app.UseWebSockets(wsOptions);
app.Use(async (context, next) =>
{
if (context.Request.Path == "/test")
{
/*TEST*/
if(context.Connection.ClientCertificate!=null) //alwayse null, why?
{ }
/*TEST*/
if (context.WebSockets.IsWebSocketRequest)
{
using var webSocket = await context.WebSockets.AcceptWebSocketAsync();
await Echo(webSocket);
}
else
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
}
}
else
{
await next(context);
}
});
i think i do somethink here wrong ?
X509Certificate2 certificate = new X509Certificate2("certPath", "password");
_clientWebSocket.Options.ClientCertificates.Add(certificate);
it could also be on the server that I maybe still have to specify something for the certificate, so much knowledge I have then unfortunately also not of
edit - I test the whole thing with swagger