.Net Aspire framework is used to develop cloud and production-ready distributed applications. It consists of components to handle cloud-native concerns such as Redis, Postgres etc.
Prerequisites:::tip 10 Day .Net Aspire Challenge
:::
ObjectivesLearn how to create a starter project using .Net Aspire with the Apache Kafka component.
Github Sample: The solution structure is divided into the following projects:
Install the following Nuget package into the subsequent project “DotnetAspireChallenge.AppHost”
dotnet add package Aspire.Hosting.Kafka\ In the above project, register Kafka UI as shown below
var messaging = builder.AddKafka("messaging") .WithKafkaUI();Then finally add a reference to both the Producer and Consumer where the producer is “DotnetAspireChallenge.ApiService” and the consumer is “DotnetAspireChallenge.Web” project respectively.
var apiService = builder.AddProject\
Step 2: Add dependency of Kafka ProducerAdd the dependency in the Program.cs file of the project “**DotnetAspireChallenge.**ApiService”
builder.AddKafkaProducer\ and add a relevant minimal API endpoint using the following code.
public static class AspireKafkaExtension { public static void MapAspireKafkaEndpoint(this WebApplication app) { app.MapGet("/send", async (IProducer\ The endpoint takes two parameters namely key and value as route values, and produces the message on the docker-hosted Kafka server.
https://localhost:7313/send?key=key&value=1\
Step 3: Add dependency of Kafka ConsumerNow move “DotnetAspireChallenge.Web” project wherein register as a Kafka producer
builder.AddKafkaConsumer:::info Note: It's mandatory to provide a default group ID.
:::
\
Step 4: Create a Razor PageCreate a basic razor page named “KafkaConsumer.razor” to show the consumed message from the Kafka server.
@page "/kafka" @attribute [StreamRendering(true)] @attribute [OutputCache(Duration = 5)] @using Confluent.KafkaThis component demonstrates showing data loaded from a backend API service.
@if (consumedMessage == null) {Loading...
} else {Topic | Value |
---|---|
@consumedMessage.Topic | @consumedMessage.Value |
\
Step 5: Configure HttpCall to the ApiService public class KafkaConsumeMessageClient(HttpClient httpClient, IConsumer\
Kafka Produce Demo\
Kafka UI Demo\
Kafka Consume Demo\
:::info Github Project: GitHub - ssukhpinder/DotnetAspireChallenge: 10 Day .Net Aspire Challenge
Cheatsheet: Cheat Sheets — .Net
:::
\
All Rights Reserved. Copyright , Central Coast Communications, Inc.