Dapr - Publish/Subscibe - Using Web APIs
Tags: dotnet, dapr, pubsub, dotnetcore
Published: 2023-11-02 19:10:39

**<u>Pre-requisites</u>**
1. Install Dapr CLI 
2. .NET 6 SDK installed.
3. Docker Desktop

**<u>Create a Web API Publish Service</u>**
- Create a ASP.Net Core Web API project with .Net 6.0 framework version. Say name of the project as _publisher_
- Add nuget package _Dapr.AspNetCore_ (I have used version 1.12.0)
- Add a directory say _dapr-components_ into your project. Add file _pubsub.yaml_ into the folder, which should look as below
```
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: myapp-pubsub
spec:
  type: pubsub.redis
  version: v1
  metadata:
    - name: redisHost
      value: localhost:6379
    - name: redisPassword
      value: ""
scopes:
  - publisher
  - subscriber
```

- 
 Add below line of code into your _program.cs_

```
builder.Services.AddDaprClient();
```
Your _program.cs_ should look as below

```
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDaprClient();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

```

- Add a WebAPI controller, say it as _PublishController.cs_. The code looks as below

```
using Dapr.Client;
using Microsoft.AspNetCore.Mvc;
using System;

namespace Publisher.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PublishController : ControllerBase
    {
        private readonly DaprClient daprClient;
        private readonly ILogger<PublishController> logger;

        public PublishController(DaprClient daprClient, ILogger<PublishController> logger) 
        { 
            this.daprClient = daprClient;
            this.logger = logger;
        }

        [HttpPost]
        public async Task Post([FromBody] string value)
        {
            await daprClient.PublishEventAsync("myapp-pubsub", "test-dapr-topic", $"{DateTime.Now} - {value}");
            logger.LogInformation($"Published data at {DateTime.Now} - {value}");
        }
    }
}
```



**<u>Create a Web API Subscribe Service</u>**
- Create a ASP.Net Core Web API project with .Net 6.0 framework version. Say name of the project as _subscriber_
- Add nuget package _Dapr.AspNetCore_ (I have used version 1.12.0)
- Add a directory say _dapr-components_ into your project. Add file _pubsub.yaml_ into the folder, which should look as below
```
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: myapp-pubsub
spec:
  type: pubsub.redis
  version: v1
  metadata:
    - name: redisHost
      value: localhost:6379
    - name: redisPassword
      value: ""
scopes:
  - publisher
  - subscriber
```

- 
 Add below two lines of code into your _program.cs_

```
/* The call to UseCloudEvents adds CloudEvents middleware into to the 
 * ASP.NET Core middleware pipeline. 
 * This middleware will unwrap requests that use the CloudEvents structured 
 * format, so the receiving method can read the event payload directly. */
app.UseCloudEvents();

/* The call to MapSubscribeHandler in the endpoint routing configuration 
 * will add a Dapr subscribe endpoint to the application.
 * 
 * This endpoint will respond to requests on /dapr/subscribe.
 * When this endpoint is called, it will automatically find all WebAPI
 * action methods decorated with the Topic attribute and instruct
 * Dapr to create subscriptions for them. */
app.MapSubscribeHandler();
```

your _program.cs_ should look as follows

```
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.UseCloudEvents();
app.MapSubscribeHandler();
app.MapControllers();
app.Run();

```

- Add a WebAPI controller, say it as _SubscriberController.cs_. The code looks as below

```
using Dapr;
using Microsoft.AspNetCore.Mvc;

namespace Subscriber.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class SubscriberController : ControllerBase
    {
        ILogger<SubscriberController> logger;

        public SubscriberController(ILogger<SubscriberController> logger)
        {
            this.logger = logger;
        }

        [Topic("myapp-pubsub", "test-dapr-topic")]
        [HttpPost("subscriber")]
        public IActionResult Post([FromBody] string value)
        {
            logger.LogInformation(value);
            return Ok(value);
        }
    }
}
```
**<u>Testing our web api's publish subscribe</u>**

- Open docker desktop
- Use below command to run publisher

`dapr run --app-id publisher --app-port <port used in launch settings for https> --app-protocol https --dapr-http-port 3608 --resources-path dapr-components -- dotnet run`
- Use below command to run subscriber

`dapr run --app-id subscriber --app-port <port used in launch settings for https> --app-protocol https --dapr-http-port 3610 --resources-path dapr-components -- dotnet run`

- Test using postman. Hit publisher endpoint. You can see in the logs that publisher published message and subscriber received message

![Image that tested pubsub of dapr](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u4so2zlev4gra283xip7.png)

**<u>Source code</u>**

[dapr-publisher](https://github.com/ashwingatadi/dapr-publisher)
[dapr-subscriber](https://github.com/ashwingatadi/dapr-subscriber)