How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project

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
    • C#
    • AWS
Step 1 - Create Project

Open Visual Studio Click on “Create a new project”
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Select ASP .NET Core Web Application option.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Add the Project name and Solution name.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Select “API” option with “.NET Core” and “ASP .NET Core 3.1” for create ASP .NET API.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Users can see the default folder structure.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Step 2 - Install Nuget Packages
 
In this step, we need to install the following NuGet packages,
  1. AWSSDK.Extensions.NETCore.Setup
  2. AWSSDK.SQS
  3. Swashbuckle.AspNetCore
  4. Swashbuckle.AspNetCore.Annotations
Now, we'll proceed to install the above package from Nuget, right-click on the S3bucketDemo project:
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Change to the “Browse” tab and type AWSSDK.Extensions.NETCore.Setup,
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
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.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Step B: After successfully download the “AWSCLIV2.msi” file then install.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Step C: For checkng if “AWSCLIV2” is installed properly then open CMD run as administrator.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Step D: execute command “aws --v” for checking if  “AWSCLIV2” is installed properly or not.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Step E: Now login to https://aws.amazon.com/ site. 
 
Step F: Search IAM in the “Find Services” textbox as per the below screenshot.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Step G: Click on the “Users” link and click on a particular user as per the below screenshot. 
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Step H: Then click on the “Security credentials” link as per the below screenshot.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Step I: Then click on the “Create access key” link as per the below screenshot.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Step J: Then copy “Access key ID”, “Secret access key” and Download .csv for feature use as per the below screenshot.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Step K: Now, come back to CMD and run “aws configure” command as per the below screenshot.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project 
  1. $ aws configure  
  2. AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE  
  3. AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY  
  4. Default region name [None]: us-west-2  
  5. Default output format [None]: json  
Reference Link.
 
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.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
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.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Step B: Click on the “Create queue” button as per the below screenshot.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
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.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Step D: Configure other options as per your requirement and click on the “Create queue” button.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Step E: Then copy your SQS URL and paste in notepad.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
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,
  1. namespace DemoAWSSQS.Models  
  2. {  
  3.     public class ServiceConfiguration  
  4.     {  
  5.         public AWSSQS AWSSQS { getset; }  
  6.     }  
  7.     public class AWSSQS  
  8.     {  
  9.         public string QueueUrl { getset; }  
  10.     }  
  11. }  
Code for UserModel.cs file,
  1. using System;  
  2. namespace DemoAWSSQS.Models  
  3. {  
  4.     public class User  
  5.     {  
  6.         public string FirstName { getset; }  
  7.         public string LastName { getset; }  
  8.         public string UserName { getset; }  
  9.         public string EmailId { getset; }  
  10.     }  
  11.     public class UserDetail: User  
  12.     {  
  13.         public int Id { getset; }  
  14.         public DateTime CreatedOn { getset; }  
  15.         public DateTime UpdatedOn { getset; }  
  16.     }  
  17.     public class AllMessage  
  18.     {  
  19.         public AllMessage()  
  20.         {  
  21.             UserDetail = new UserDetail();  
  22.         }  
  23.         public string MessageId { getset; }  
  24.         public string ReceiptHandle { getset; }  
  25.   
  26.         public UserDetail UserDetail { getset; }  
  27.     }  
  28.     public class DeleteMessage  
  29.     {  
  30.         public string ReceiptHandle { getset; }  
  31.     }  
  32. }  
Step 6 - Update appsettings.Development.json
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Code for appsettings.Development.json file,
  1. {    
  2.   "Logging": {    
  3.     "LogLevel": {    
  4.       "Default""Information",    
  5.       "Microsoft""Warning",    
  6.       "Microsoft.Hosting.Lifetime""Information"    
  7.     }    
  8.   },    
  9.   "ServiceConfiguration": {    
  10.     "AWSSQS": {    
  11.       "QueueUrl""*SQS_URL*"    
  12.     }    
  13.   }    
  14. }    
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
  1. using Amazon.SQS;  
  2. using Amazon.SQS.Model;  
  3. using DemoAWSSQS.Models;  
  4. using Microsoft.Extensions.Options;  
  5. using Newtonsoft.Json;  
  6. using System;  
  7. using System.Collections.Generic;  
  8. using System.Linq;  
  9. using System.Threading.Tasks;  
  10. namespace DemoAWSSQS.Helpers  
  11. {  
  12.     public interface IAWSSQSHelper  
  13.     {  
  14.         Task<bool> SendMessageAsync(UserDetail userDetail);  
  15.         Task<List<Message>> ReceiveMessageAsync();  
  16.         Task<bool> DeleteMessageAsync(string messageReceiptHandle);  
  17.     }  
  18.     public class AWSSQSHelper: IAWSSQSHelper  
  19.     {  
  20.         private readonly IAmazonSQS _sqs;  
  21.         private readonly ServiceConfiguration _settings;  
  22.         public AWSSQSHelper(  
  23.            IAmazonSQS sqs,  
  24.            IOptions<ServiceConfiguration> settings)  
  25.         {  
  26.             this._sqs = sqs;  
  27.             this._settings = settings.Value;  
  28.         }  
  29.         public async Task<bool> SendMessageAsync(UserDetail userDetail)  
  30.         {  
  31.             try  
  32.             {  
  33.                 string message = JsonConvert.SerializeObject(userDetail);  
  34.                 var sendRequest = new SendMessageRequest(_settings.AWSSQS.QueueUrl, message);  
  35.                 // Post message or payload to queue  
  36.                 var sendResult = await _sqs.SendMessageAsync(sendRequest);  
  37.   
  38.                 return sendResult.HttpStatusCode == System.Net.HttpStatusCode.OK;  
  39.             }  
  40.             catch (Exception ex)  
  41.             {  
  42.                 throw ex;  
  43.             }  
  44.         }  
  45.         public async Task<List<Message>> ReceiveMessageAsync()  
  46.         {  
  47.             try  
  48.             {  
  49.                 //Create New instance  
  50.                 var request = new ReceiveMessageRequest  
  51.                 {  
  52.                     QueueUrl = _settings.AWSSQS.QueueUrl,  
  53.                     MaxNumberOfMessages = 10,  
  54.                     WaitTimeSeconds = 5  
  55.                 };  
  56.                 //CheckIs there any new message available to process  
  57.                 var result = await _sqs.ReceiveMessageAsync(request);  
  58.                       
  59.                 return result.Messages.Any() ? result.Messages : new List<Message>();  
  60.             }  
  61.             catch (Exception ex)  
  62.             {  
  63.                 throw ex;  
  64.             }  
  65.         }  
  66.         public async Task<bool> DeleteMessageAsync(string messageReceiptHandle)  
  67.         {  
  68.             try  
  69.             {  
  70.                 //Deletes the specified message from the specified queue  
  71.                 var deleteResult = await _sqs.DeleteMessageAsync(_settings.AWSSQS.QueueUrl, messageReceiptHandle);  
  72.                 return deleteResult.HttpStatusCode == System.Net.HttpStatusCode.OK;  
  73.             }  
  74.             catch (Exception ex)  
  75.             {  
  76.                 throw ex;  
  77.             }  
  78.         }  
  79.     }  
  80. }  
Step 8 - Create Service
 
Now, create a directory with the name Services and add the following files:
 
AWSSQSService.cs
  1. using Amazon.SQS.Model;  
  2. using DemoAWSSQS.Helpers;  
  3. using DemoAWSSQS.Models;  
  4. using Newtonsoft.Json;  
  5. using System;  
  6. using System.Collections.Generic;  
  7. using System.Linq;  
  8. using System.Threading.Tasks;  
  9.   
  10. namespace DemoAWSSQS.Services  
  11. {  
  12.     public interface IAWSSQSService  
  13.     {  
  14.         Task<bool> PostMessageAsync(User user);  
  15.         Task<List<AllMessage>> GetAllMessagesAsync();  
  16.         Task<bool> DeleteMessageAsync(DeleteMessage deleteMessage);  
  17.     }  
  18.     public class AWSSQSService : IAWSSQSService  
  19.     {  
  20.         private readonly IAWSSQSHelper _AWSSQSHelper;  
  21.         public AWSSQSService(IAWSSQSHelper AWSSQSHelper)  
  22.         {  
  23.             this._AWSSQSHelper = AWSSQSHelper;  
  24.         }  
  25.         public async Task<bool> PostMessageAsync(User user)  
  26.         {  
  27.             try  
  28.             {  
  29.                 UserDetail userDetail = new UserDetail();  
  30.                 userDetail.Id = new Random().Next(999999999);  
  31.                 userDetail.FirstName = user.FirstName;  
  32.                 userDetail.LastName = user.LastName;  
  33.                 userDetail.UserName = user.UserName;  
  34.                 userDetail.EmailId = user.EmailId;  
  35.                 userDetail.CreatedOn = DateTime.UtcNow;  
  36.                 userDetail.UpdatedOn = DateTime.UtcNow;  
  37.                 return await _AWSSQSHelper.SendMessageAsync(userDetail);  
  38.             }  
  39.             catch (Exception ex)  
  40.             {  
  41.                 throw ex;  
  42.             }  
  43.         }  
  44.         public async Task<List<AllMessage>> GetAllMessagesAsync()  
  45.         {  
  46.             List<AllMessage> allMessages = new List<AllMessage>();  
  47.             try  
  48.             {  
  49.                 List<Message> messages = await _AWSSQSHelper.ReceiveMessageAsync();  
  50.                 allMessages = messages.Select(c => new AllMessage { MessageId = c.MessageId, ReceiptHandle = c.ReceiptHandle, UserDetail = JsonConvert.DeserializeObject<UserDetail>(c.Body) }).ToList();  
  51.                 return allMessages;  
  52.             }  
  53.             catch (Exception ex)  
  54.             {  
  55.                 throw ex;  
  56.             }  
  57.         }  
  58.   
  59.         public async Task<bool> DeleteMessageAsync(DeleteMessage deleteMessage)  
  60.         {  
  61.             try  
  62.             {  
  63.                 return await _AWSSQSHelper.DeleteMessageAsync(deleteMessage.ReceiptHandle);  
  64.             }  
  65.             catch (Exception ex)  
  66.             {  
  67.                 throw ex;  
  68.             }  
  69.         }  
  70.     }  
  71. }  
Step 9 - Update Startup.cs
 
Code for Startup.cs file,
  1. using Amazon.SQS;  
  2. using DemoAWSSQS.Helpers;  
  3. using DemoAWSSQS.Models;  
  4. using DemoAWSSQS.Services;  
  5. using Microsoft.AspNetCore.Builder;  
  6. using Microsoft.AspNetCore.Hosting;  
  7. using Microsoft.Extensions.Configuration;  
  8. using Microsoft.Extensions.DependencyInjection;  
  9. using Microsoft.Extensions.Hosting;  
  10. using Microsoft.OpenApi.Models;  
  11.   
  12. namespace DemoAWSSQS  
  13. {  
  14.     public class Startup  
  15.     {  
  16.         public Startup(IConfiguration configuration)  
  17.         {  
  18.             Configuration = configuration;  
  19.         }  
  20.         readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";  
  21.         public IConfiguration Configuration { get; }  
  22.   
  23.         // This method gets called by the runtime. Use this method to add services to the container.  
  24.         public void ConfigureServices(IServiceCollection services)  
  25.         {  
  26.             services.AddControllers();  
  27.             var appSettingsSection = Configuration.GetSection("ServiceConfiguration");  
  28.             services.AddAWSService<IAmazonSQS>();  
  29.             services.Configure<ServiceConfiguration>(appSettingsSection);  
  30.             services.AddTransient<IAWSSQSService, AWSSQSService>();  
  31.             services.AddTransient<IAWSSQSHelper, AWSSQSHelper>();  
  32.   
  33.             services.AddSwaggerGen(c =>  
  34.             {  
  35.                 c.SwaggerDoc("v1"new OpenApiInfo { Title = "My API", Version = "v1" });  
  36.             });  
  37.             services.AddCors(options =>  
  38.             {  
  39.                 options.AddPolicy(name: MyAllowSpecificOrigins, builder =>  
  40.                 builder  
  41.                 .AllowAnyOrigin()  
  42.                 .AllowAnyMethod()  
  43.                 .AllowAnyHeader());  
  44.                 // .AllowCredentials());  
  45.             });  
  46.         }  
  47.   
  48.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  49.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  50.         {  
  51.             if (env.IsDevelopment())  
  52.             {  
  53.                 app.UseDeveloperExceptionPage();  
  54.             }  
  55.   
  56.             app.UseHttpsRedirection();  
  57.   
  58.             app.UseRouting();  
  59.   
  60.             app.UseAuthorization();  
  61.             app.UseCors(MyAllowSpecificOrigins);  
  62.             // Enable middleware to serve generated Swagger as a JSON endpoint.  
  63.             app.UseSwagger();  
  64.             // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),  
  65.             // specifying the Swagger JSON endpoint.  
  66.             app.UseSwaggerUI(c =>  
  67.             {  
  68.                 c.SwaggerEndpoint("/swagger/v1/swagger.json""My API V1");  
  69.             });  
  70.   
  71.             app.UseEndpoints(endpoints =>  
  72.             {  
  73.                 endpoints.MapControllers();  
  74.             });  
  75.         }  
  76.     }  
  77. }  
Step 10 - Add Controller
 
Now, add the AWSSQSController.cs files in Controllers folder,
  1. using DemoAWSSQS.Models;  
  2. using DemoAWSSQS.Services;  
  3. using Microsoft.AspNetCore.Mvc;  
  4. using System.Threading.Tasks;  
  5.   
  6. namespace DemoAWSSQS.Controllers  
  7. {  
  8.     [Produces("application/json")]  
  9.     [Route("api/[controller]")]  
  10.     [ApiController]  
  11.     public class AWSSQSController : ControllerBase  
  12.     {  
  13.         private readonly IAWSSQSService _AWSSQSService;  
  14.   
  15.         public AWSSQSController(IAWSSQSService AWSSQSService)  
  16.         {  
  17.             this._AWSSQSService = AWSSQSService;  
  18.         }  
  19.   
  20.         [Route("postMessage")]  
  21.         [HttpPost]  
  22.         public async Task<IActionResult> PostMessageAsync([FromBody] User user)  
  23.         {  
  24.             var result = await _AWSSQSService.PostMessageAsync(user);  
  25.             return Ok(new { isSucess = result });  
  26.         }  
  27.         [Route("getAllMessages")]  
  28.         [HttpGet]  
  29.         public async Task<IActionResult> GetAllMessagesAsync()  
  30.         {  
  31.             var result = await _AWSSQSService.GetAllMessagesAsync();  
  32.             return Ok(result);  
  33.         }  
  34.         [Route("deleteMessage")]  
  35.         [HttpDelete]  
  36.         public async Task<IActionResult> DeleteMessageAsync(DeleteMessage deleteMessage)  
  37.         {  
  38.             var result = await _AWSSQSService.DeleteMessageAsync(deleteMessage);  
  39.             return Ok(new { isSucess = result });  
  40.         }  
  41.     }  
  42. }  
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:
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Now we have to open “/Swagger” for executing API for Send and Received Message in AWS SQS.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
Send Message to AWS SQS
 
Click on “/api​/AWSSQS​/postMessage” tab and click on the “Try it out” button as per the below screenshot.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
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.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
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.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project
 
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.
 
How To Implement Amazon SQS (AWS SQS) In ASP.NET Core Project