Introduction
Basically in this article, we will learn how to implement Amazon SQS (AWS SQS) in an ASP .Net Core project, how to create SQS on AWS, how to send message to AWS SQS, how to receive a message from AWS SQS and how to delete a message from AWS SQS in ASP.net Core.
Prerequisites
- Software
- Dot NET Core
- Visual Studio 2017 with last update or Visual Studio 2019
- Skills
Step 1 - Create Project
Open Visual Studio Click on “Create a new project”
Select ASP .NET Core Web Application option.
Add the Project name and Solution name.
Select “API” option with “.NET Core” and “ASP .NET Core 3.1” for create ASP .NET API.
Users can see the default folder structure.
Step 2 - Install Nuget Packages
In this step, we need to install the following NuGet packages,
- AWSSDK.Extensions.NETCore.Setup
- AWSSDK.SQS
- Swashbuckle.AspNetCore
- Swashbuckle.AspNetCore.Annotations
Now, we'll proceed to install the above package from Nuget, right-click on the S3bucketDemo project:
Change to the “Browse” tab and type AWSSDK.Extensions.NETCore.Setup,
Next,
Install AWSSDK.SQS package
Install AWSSDK.Extensions.NETCore.Setup package
Install Swashbuckle.AspNetCore package
Install Swashbuckle.AspNetCore.Annotations package
Step 3 - Now, we have to Install and Configure AWS CLI in our Windows computer
Step A: Go to
here site and click on “Download and run the
64-bit Windows installer” link as per the below screenshot.
Step B: After successfully download the “AWSCLIV2.msi” file then install.
Step C: For checkng if “AWSCLIV2” is installed properly then open CMD run as administrator.
Step D: execute command “aws --v” for checking if “AWSCLIV2” is installed properly or not.
Step E: Now login to https://aws.amazon.com/ site.
Step F: Search IAM in the “Find Services” textbox as per the below screenshot.
Step G: Click on the “Users” link and click on a particular user as per the below screenshot.
Step H: Then click on the “Security credentials” link as per the below screenshot.
Step I: Then click on the “Create access key” link as per the below screenshot.
Step J: Then copy “Access key ID”, “Secret access key” and Download .csv for feature use as per the below screenshot.
Step K: Now, come back to CMD and run “aws configure” command as per the below screenshot.
- $ aws configure
- AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
- AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
- Default region name [None]: us-west-2
- Default output format [None]: json
Step L: Open “File Explorer” and go to your user name folder like “C:\Users\UserName” and open the “.aws” folder as per the below screenshot.
Step 4 - Now, we have to create SQS on AWS.
Step A: Go to the AWS dashboard and Search “SQS” in the “Find Services” textbox as per the below screenshot.
Step B: Click on the “Create queue” button as per the below screenshot.
Step C: Add queue “Name” in the textbox and select any option from “Standard” to “FIFO” as per your requirement, as per the below screenshot.
Step D: Configure other options as per your requirement and click on the “Create queue” button.
Step E: Then copy your SQS URL and paste in notepad.
Step 5 - Now we Create Models.
Now, create a directory with the name Models and add the following files:
ServiceConfiguration.cs
UserModel.cs
Code for ServiceConfiguration.cs file,
- namespace DemoAWSSQS.Models
- {
- public class ServiceConfiguration
- {
- public AWSSQS AWSSQS { get; set; }
- }
- public class AWSSQS
- {
- public string QueueUrl { get; set; }
- }
- }
Code for UserModel.cs file,
- using System;
- namespace DemoAWSSQS.Models
- {
- public class User
- {
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string UserName { get; set; }
- public string EmailId { get; set; }
- }
- public class UserDetail: User
- {
- public int Id { get; set; }
- public DateTime CreatedOn { get; set; }
- public DateTime UpdatedOn { get; set; }
- }
- public class AllMessage
- {
- public AllMessage()
- {
- UserDetail = new UserDetail();
- }
- public string MessageId { get; set; }
- public string ReceiptHandle { get; set; }
-
- public UserDetail UserDetail { get; set; }
- }
- public class DeleteMessage
- {
- public string ReceiptHandle { get; set; }
- }
- }
Step 6 - Update appsettings.Development.json
Code for appsettings.Development.json file,
- {
- "Logging": {
- "LogLevel": {
- "Default": "Information",
- "Microsoft": "Warning",
- "Microsoft.Hosting.Lifetime": "Information"
- }
- },
- "ServiceConfiguration": {
- "AWSSQS": {
- "QueueUrl": "*SQS_URL*"
- }
- }
- }
Replace *SQS_URL* with your SQS URL which you stored in notepad.
Step 7 - Create Helpers
Now, create a directory with the name Helpers and add the following files,
AWSSQSHelper.cs
- using Amazon.SQS;
- using Amazon.SQS.Model;
- using DemoAWSSQS.Models;
- using Microsoft.Extensions.Options;
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- namespace DemoAWSSQS.Helpers
- {
- public interface IAWSSQSHelper
- {
- Task<bool> SendMessageAsync(UserDetail userDetail);
- Task<List<Message>> ReceiveMessageAsync();
- Task<bool> DeleteMessageAsync(string messageReceiptHandle);
- }
- public class AWSSQSHelper: IAWSSQSHelper
- {
- private readonly IAmazonSQS _sqs;
- private readonly ServiceConfiguration _settings;
- public AWSSQSHelper(
- IAmazonSQS sqs,
- IOptions<ServiceConfiguration> settings)
- {
- this._sqs = sqs;
- this._settings = settings.Value;
- }
- public async Task<bool> SendMessageAsync(UserDetail userDetail)
- {
- try
- {
- string message = JsonConvert.SerializeObject(userDetail);
- var sendRequest = new SendMessageRequest(_settings.AWSSQS.QueueUrl, message);
-
- var sendResult = await _sqs.SendMessageAsync(sendRequest);
-
- return sendResult.HttpStatusCode == System.Net.HttpStatusCode.OK;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- public async Task<List<Message>> ReceiveMessageAsync()
- {
- try
- {
-
- var request = new ReceiveMessageRequest
- {
- QueueUrl = _settings.AWSSQS.QueueUrl,
- MaxNumberOfMessages = 10,
- WaitTimeSeconds = 5
- };
-
- var result = await _sqs.ReceiveMessageAsync(request);
-
- return result.Messages.Any() ? result.Messages : new List<Message>();
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- public async Task<bool> DeleteMessageAsync(string messageReceiptHandle)
- {
- try
- {
-
- var deleteResult = await _sqs.DeleteMessageAsync(_settings.AWSSQS.QueueUrl, messageReceiptHandle);
- return deleteResult.HttpStatusCode == System.Net.HttpStatusCode.OK;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- }
- }
Step 8 - Create Service
Now, create a directory with the name Services and add the following files:
AWSSQSService.cs
- using Amazon.SQS.Model;
- using DemoAWSSQS.Helpers;
- using DemoAWSSQS.Models;
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace DemoAWSSQS.Services
- {
- public interface IAWSSQSService
- {
- Task<bool> PostMessageAsync(User user);
- Task<List<AllMessage>> GetAllMessagesAsync();
- Task<bool> DeleteMessageAsync(DeleteMessage deleteMessage);
- }
- public class AWSSQSService : IAWSSQSService
- {
- private readonly IAWSSQSHelper _AWSSQSHelper;
- public AWSSQSService(IAWSSQSHelper AWSSQSHelper)
- {
- this._AWSSQSHelper = AWSSQSHelper;
- }
- public async Task<bool> PostMessageAsync(User user)
- {
- try
- {
- UserDetail userDetail = new UserDetail();
- userDetail.Id = new Random().Next(999999999);
- userDetail.FirstName = user.FirstName;
- userDetail.LastName = user.LastName;
- userDetail.UserName = user.UserName;
- userDetail.EmailId = user.EmailId;
- userDetail.CreatedOn = DateTime.UtcNow;
- userDetail.UpdatedOn = DateTime.UtcNow;
- return await _AWSSQSHelper.SendMessageAsync(userDetail);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- public async Task<List<AllMessage>> GetAllMessagesAsync()
- {
- List<AllMessage> allMessages = new List<AllMessage>();
- try
- {
- List<Message> messages = await _AWSSQSHelper.ReceiveMessageAsync();
- allMessages = messages.Select(c => new AllMessage { MessageId = c.MessageId, ReceiptHandle = c.ReceiptHandle, UserDetail = JsonConvert.DeserializeObject<UserDetail>(c.Body) }).ToList();
- return allMessages;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
-
- public async Task<bool> DeleteMessageAsync(DeleteMessage deleteMessage)
- {
- try
- {
- return await _AWSSQSHelper.DeleteMessageAsync(deleteMessage.ReceiptHandle);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- }
- }
Step 9 - Update Startup.cs
Code for Startup.cs file,
- using Amazon.SQS;
- using DemoAWSSQS.Helpers;
- using DemoAWSSQS.Models;
- using DemoAWSSQS.Services;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.OpenApi.Models;
-
- namespace DemoAWSSQS
- {
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
- readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
- public IConfiguration Configuration { get; }
-
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddControllers();
- var appSettingsSection = Configuration.GetSection("ServiceConfiguration");
- services.AddAWSService<IAmazonSQS>();
- services.Configure<ServiceConfiguration>(appSettingsSection);
- services.AddTransient<IAWSSQSService, AWSSQSService>();
- services.AddTransient<IAWSSQSHelper, AWSSQSHelper>();
-
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
- });
- services.AddCors(options =>
- {
- options.AddPolicy(name: MyAllowSpecificOrigins, builder =>
- builder
- .AllowAnyOrigin()
- .AllowAnyMethod()
- .AllowAnyHeader());
-
- });
- }
-
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
-
- app.UseHttpsRedirection();
-
- app.UseRouting();
-
- app.UseAuthorization();
- app.UseCors(MyAllowSpecificOrigins);
-
- app.UseSwagger();
-
-
- app.UseSwaggerUI(c =>
- {
- c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
- });
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
- }
- }
Step 10 - Add Controller
Now, add the AWSSQSController.cs files in Controllers folder,
- using DemoAWSSQS.Models;
- using DemoAWSSQS.Services;
- using Microsoft.AspNetCore.Mvc;
- using System.Threading.Tasks;
-
- namespace DemoAWSSQS.Controllers
- {
- [Produces("application/json")]
- [Route("api/[controller]")]
- [ApiController]
- public class AWSSQSController : ControllerBase
- {
- private readonly IAWSSQSService _AWSSQSService;
-
- public AWSSQSController(IAWSSQSService AWSSQSService)
- {
- this._AWSSQSService = AWSSQSService;
- }
-
- [Route("postMessage")]
- [HttpPost]
- public async Task<IActionResult> PostMessageAsync([FromBody] User user)
- {
- var result = await _AWSSQSService.PostMessageAsync(user);
- return Ok(new { isSucess = result });
- }
- [Route("getAllMessages")]
- [HttpGet]
- public async Task<IActionResult> GetAllMessagesAsync()
- {
- var result = await _AWSSQSService.GetAllMessagesAsync();
- return Ok(result);
- }
- [Route("deleteMessage")]
- [HttpDelete]
- public async Task<IActionResult> DeleteMessageAsync(DeleteMessage deleteMessage)
- {
- var result = await _AWSSQSService.DeleteMessageAsync(deleteMessage);
- return Ok(new { isSucess = result });
- }
- }
- }
Step 11 - Running Web API
Now, press F5 to start debugging for the Web API project, if everything it's OK, we'll get the following output in the browser:
Now we have to open “/Swagger” for executing API for Send and Received Message in AWS SQS.
Send Message to AWS SQS
Click on “/api/AWSSQS/postMessage” tab and click on the “Try it out” button as per the below screenshot.
Now add user details for sending a message to AWS SQS and click on the “Execute” button then you can see the API response as per the below screenshot.
Receive a message from AWS SQS
Click on “/api/AWSSQS/getAllMessages” tab and click on “Try it out” then click on the “Execute” button then you can see the API response as per the below screenshot.
Delete message from AWS SQS
Copy any message receiptHandle from “/api/AWSSQS/getAllMessages” response and click on "/api/AWSSQS/deleteMessage” tab and click on “Try it out” then paste receiptHandle then click on the “Execute” button then you can see the API response as per the below screenshot.