How to Integrate mCore .NET SMS Library into Your .NET Project
Prerequisites
- .NET SDK: .NET 6 or later (assumed).
- IDE: Visual Studio 2022 / VS Code.
- NuGet access: Ability to add packages from nuget.org or a private feed.
- Credentials: API key and endpoint for your mCore SMS account.
1. Install the package
Use the NuGet package (assumed package ID: mCore.Sms). From a terminal in your project folder:
bash
dotnet add package mCore.Sms
Or via Package Manager Console:
powershell
Install-Package mCore.Sms
2. Configure settings
Add your mCore credentials and options to appsettings.json:
json
{ “mCoreSms”: { “ApiKey”: “YOUR_APIKEY”, “BaseUrl”: “https://api.mcore.example”, “DefaultSender”: “MyApp” } }
Bind the settings in Program.cs (minimal API / .NET 6+):
csharp
builder.Services.Configure<MCoreSmsOptions>(builder.Configuration.GetSection(“mCoreSms”)); builder.Services.AddSingleton<IMCoreSmsClient, MCoreSmsClient>();
3. Initialize the client
If the library exposes a factory or client, register and use it. Example usage:
csharp
public class NotificationService { private readonly IMCoreSmsClient _smsClient; public NotificationService(IMCoreSmsClient smsClient) => _smsClient = smsClient; public async Task SendWelcomeAsync(string phoneNumber, string message) { var request = new SmsRequest { To = phoneNumber, From = “MyApp”, Body = message }; var result = await smsClient.SendSmsAsync(request); if (!result.IsSuccess) throw new Exception($“SMS failed: {result.ErrorMessage}”); } }
4. Handle delivery reports and webhooks
- Configure a webhook endpoint in your app to receive delivery callbacks.
- Expose an endpoint and validate requests (HMAC or token) as documented by mCore. Example controller:
csharp
[HttpPost(“api/sms/webhook”)] public IActionResult SmsWebhook([FromBody] DeliveryReport report) { // validate signature, update message status in DB return Ok(); }
5. Error handling and retries
- Inspect SendSmsAsync result for transient failures and implement exponential backoff retries.
- Log request/response IDs for debugging and support.
6. Testing and local development
- Use test/sandbox API keys if provided.
- Mock IMCoreSmsClient in unit tests:
csharp
var mock = new Mock<IMCoreSmsClient>(); mock.Setup(m => m.SendSmsAsync(It.IsAny<SmsRequest>())).ReturnsAsync(new SmsResult { IsSuccess = true });
7. Security and best practices
- Store API keys in environment variables or a secrets store, not in source control.
- Rate-limit outgoing messages to comply with provider limits.
- Validate and sanitize phone numbers (E.164 format).
8. Monitoring and metrics
- Track message counts, success/failure rates, latency.
- Expose metrics to Prometheus/Application Insights for alerts.
If you want, I can adapt these steps into a ready-to-run sample project (Program.cs, appsettings.json, and minimal controller).
Leave a Reply