Design SMS Message Payload
Use a structured payload to handle metadata and SMS content:
{
"api_token": "your-api-token",
"sid": "SERVICE_ID",
"msisdn": "88019XXXXXXXX",
"sms_body": "Hello, your OTP is 123456",
"csms_id": "unique_id_for_tracking"
}
Create a WebAPI project
dotnet new webapi -n MyWebApiProject
NuGet Packages:
Install the necessary MassTransit and RabbitMQ packages:
dotnet add package MassTransit
dotnet add package MassTransit.RabbitMQ
Config RabbitMQ
Configure the connection to your RabbitMQ instance in appsettings.json:
"RabbitMQ": {
"HostName": "your_rabbitmq_host",
"UserName": "your_username",
"Password": "your_password"
}
Create SMS Message Model
Define a model for your SMS messages:
public class SmsMessage
{
public string api_token { get; set; }
public string sid { get; set; }
public string msisdn { get; set; }
public string sms_body { get; set; }
public string csms_id { get; set; }
}
Producer (API Gateway):
Publish SMS messages to the RabbitMQ queue:
public class SmsService : ISmsService
{
private readonly IPublishEndpoint _publishEndpoint;
public SmsService(IPublishEndpoint publishEndpoint)
{
_publishEndpoint = publishEndpoint;
}
public async Task SendSmsAsync(SmsMessage message)
{
await _publishEndpoint.Publish(message);
}
}
Consumer (SMS Worker):
Consume messages from the queue and send SMS using a chosen provider:
public class SmsWorker : IConsumer<SmsMessage>
{
private readonly ISmsProvider _smsProvider;
public SmsWorker(ISmsProvider smsProvider)
{
_smsProvider = smsProvider;
}
public async Task Consume(ConsumeContext<SmsMessage> context)
{
var message = context.Message;
await _smsProvider.SendSmsAsync(message.To, message.From, message.Body);
}
}
SMS Provider Interface:
Define an interface for interacting with different SMS providers:
public interface ISmsProvider
{
Task SendSmsAsync(string to, string from, string body);
}
MassTransit Configuration:
Configure MassTransit in your Program.cs:
builder.Services.AddMassTransit(x =>
{
x.AddConsumer<SmsWorker>();
x.UsingRabbitMq((context, cfg) =>
{
cfg.Host(configuration["RabbitMQ:HostName"], "/", h =>
{
h.Username(configuration["RabbitMQ:UserName"]);
h.Password(configuration["RabbitMQ:Password"]);
});
cfg.ReceiveEndpoint("sms_queue", e =>
{
e.ConfigureConsumer<SmsWorker>(context);
});
});
});
builder.Services.AddMassTransitHostedService();
Run & Test