Every now and then you are thrown into projects were you might not be the perfect pick from start. I seldom work with .NET and this project was just that
I was asked to create a small .NET proof-of-concept application in C# that fetches messages from a AMQP broker using mTLS authentication. I post the solution so it might benefit someone else (did not find much about this on Google)
Here is the result:
03 | using Microsoft.Extensions.Logging; |
10 | static async Task Main( string [] args) |
12 | using var loggerFactory = LoggerFactory.Create(builder => |
16 | .SetMinimumLevel(LogLevel.Debug); |
19 | ILogger logger = loggerFactory.CreateLogger<Program>(); |
21 | logger.LogInformation( "Application started." ); |
25 | var factory = new ConnectionFactory(); |
26 | factory.SSL.ClientCertificates.Add( new |
27 | System.Security.Cryptography.X509Certificates |
28 | .X509Certificate2( "c:\\myclientcert.pfx" , "secret" )); |
30 | factory.SASL.Profile = SaslProfile.Anonymous; |
33 | logger.LogInformation( "Connecting to broker..." ); |
34 | Connection connection = await factory.CreateAsync(address); |
35 | logger.LogInformation( "Connected to broker." ); |
37 | Session session = new Session(connection); |
38 | ReceiverLink receiver = |
39 | new ReceiverLink(session, "receiver-link" , "MYQUEU" ); |
41 | Console.WriteLine( "Receiver connected to broker." ); |
43 | Message message = await Task.Run(() => |
44 | receiver.Receive(TimeSpan.FromMilliseconds(2000))); |
48 | Console.WriteLine( "No message received." ); |
55 | Console.WriteLine( "Received " + message.Body); |
56 | receiver.Accept(message); |
64 | logger.LogError(e, "An error while processing messages." ); |
67 | logger.LogInformation( "Application ended." ); |
Tested on Windows 10, AMQPNETLite v2.4.11, .NET 8.0 and Visual Studio Code 1.97.0