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 a 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

  1. Software
    • Dot NET Core
    • Visual Studio 2017 with last update or Visual Studio 2019
  2. Skills
    • C#
    • AWS

Step 1. Create Project.

Open Visual Studio Click on “Create a new project”

Create a new project

Select the ASP .NET Core Web Application option.

Web Application

Add the Project name and Solution name.

Project name

Select the “API” option with “.NET Core” and “ASP .NET Core 3.1” to create ASP .NET API.

NET API

Users can see the default folder structure.

Folder structure

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:

Nuget Packages

Change to the “Browse” tab and type AWSSDK.Extensions.NETCore.Setup.

Browse

Next,

  1. Install AWSSDK.SQS package
  2. Install AWSSDK.Extensions.NETCore.Setup package
  3. Install Swashbuckle.AspNetCore package
  4. Install Swashbuckle.AspNetCore.Annotations package

Step 3. Now, we have to Install and Configure AWS CLI on our Windows computer.

  1. Step A: Go to the site and click on the “Download and run the 64-bit Windows installer” link as per the below screenshot.
    Download
  2. Step B: After successfully downloading the “AWSCLIV2.msi” file then install.
    AWSCLI
  3. Step C: To check if “AWSCLIV2” is installed properly then open CMD and run as administrator.
    CMD run
  4. Step D: execute the command “aws --v” to check if “AWSCLIV2” is installed properly or not.
    Execute command
  5. Step E: Now login to https://aws.amazon.com/ site.
  6. Step F: Search IAM in the “Find Services” textbox as per the below screenshot.
    Find Services
  7. Step G: Click on the “Users” link and click on a particular user as per the below screenshot.
    Users
  8. Step H: Then click on the “Security credentials” link as per the below screenshot.
    Security credentials
  9. Step I: Then click on the “Create access key” link as per the below screenshot.
    Create access key
  10. Step J: Then copy “Access key ID”, and “Secret access key” and Download .csv for feature use as per the below screenshot.
    Access key ID
  11. Step K: Now, come back to CMD and run the “aws configure” command as per the below screenshot.
    Aws configure
  12. $ aws configure
  13. AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
  14. AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
  15. Default region name [None]: us-west-2
  16. Default output format [None]: json
  17. Reference: Link.
  18. 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.
    File Explorer

Step 4. Now, we have to create SQS on AWS.

  1. Step A: Go to the AWS dashboard and Search “SQS” in the “Find Services” textbox as per the below screenshot.
    SQS
  2. Step B: Click on the “Create queue” button as per the below screenshot.
    Create queue
  3. 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.
    Standard
  4. Step D: Configure other options as per your requirement and click on the “Create queue” button.
    Requirement
  5. Step E: Then copy your SQS URL and paste into Notepad.
    SQS URL

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.

Development

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);
                // Post message or payload to queue
                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
            {
                // Create new instance
                var request = new ReceiveMessageRequest
                {
                    QueueUrl = _settings.AWSSQS.QueueUrl,
                    MaxNumberOfMessages = 10,
                    WaitTimeSeconds = 5
                };
                // Check if there are any new messages available to process
                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
            {
                // Deletes the specified message from the specified queue
                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; }

        // This method gets called by the runtime. Use this method to add services to the container.
        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());
                    //.AllowCredentials());
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseCors(MyAllowSpecificOrigins);

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            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 the 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 { isSuccess = 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 { isSuccess = 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.

Web API

Now we have to open “/Swagger” for executing API for Send and Received Message in AWS SQS.

Swagger

Send a Message to AWS SQS

Click on “/API/AWSSQS​/postMessage” tab and click on the “Try it out” button as per the below screenshot.

Send Message

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.

Execute

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.

API response

Delete message from AWS SQS

Copy any message receiptHandle from the “/API/AWSSQS/getAllMessages” response and click on the "/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.

Delete message


Similar Articles