Connect and Publish to AWS IoT Core using the AWS SDK for .NET

4 minute read
Content level: Advanced
0

An example for connecting and publishing an MQTT message to AWS IoT Core with .NET

The .NET Framework is used in a variety of applications including web, mobile, and desktops. The AWS SDK for .NET provides libraries that simplify the use of AWS Services for .NET developers.

This basic tutorial shows how to use the AWS SDK for .NET to connect and publish a message to AWS IoT Core. The tutorial also lists the AWS profile user, the AWS IoT Endpoint for the profile user’s AWS account, and returns the result of the publish request.

Steps

  • Create the project
  • Create the code
  • Run the application
  • Cleanup

Create the project

  1. Open the command prompt or terminal. Find or create an operating system folder under which you can create a .NET project.
  2. In that folder, run the following command to create the .NET project.
dotnet new console --name AWSIoTPublish
  1. Go to the newly created AWSIoTPublish folder and run the following commands. The packages will be installed with the NuGet package manager.
dotnet add package AWSSDK.IoT
dotnet add package AWSSDK.IoT.Model
dotnet add package AWSSDK.IoTData
dotnet add package AWSSDK.SecurityToken
dotnet add package AWSSDK.SSO
dotnet add package AWSSDK.SSOOIDC`

Create the code

  1. In the AWSIoTPublish folder, find and open Program.cs in your code editor.
  2. Replace the contents with the following code and save the file.
// NuGet packages
using Amazon.Runtime;
using Amazon.Runtime.CredentialManagement;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;
using Amazon.IotData;
using Amazon.IoT;
using Amazon.IoT.Model;

namespace IoTConnectandPublish
{
    class Program
    {
        // Class members
        static async Task Main(string[] args)
        {
            // Get credentials from the information in the shared config file
            var creds = LoadSsoCredentials("default");

            // Display the caller's identity
            var ssoProfileClient = new AmazonSecurityTokenServiceClient(creds);
            Console.WriteLine($"\nSSO Profile:\n {await ssoProfileClient.GetCallerIdentityArn()}");
            
            // Get AWS IoT ATS Endpoint
            using var iotclient = new AmazonIoTClient();
            var request = new DescribeEndpointRequest
                {
                    EndpointType = "iot:Data-ATS"
                };
            var response = await iotclient.DescribeEndpointAsync(request);
            Console.WriteLine($"\nAWS IoT Endpoint:\n {response.EndpointAddress}");
            
            // Create IoT client and publish a message
            var endpoint = "https://" + response.EndpointAddress;
            var dataclient = new AmazonIotDataClient(endpoint);
            var payload = new System.IO.MemoryStream(System.Text.Encoding.ASCII.GetBytes("{\"message\":\"Hello world!\"}"));
            var message = new Amazon.IotData.Model.PublishRequest
                {
                    ContentType = "application/json",
                    Topic = "test/topic",
                    Payload = payload
                };
            Console.WriteLine($"\nPublishing message to AWS IoT Core on topic:\n {message.Topic}");
            var publish = await dataclient.PublishAsync(message);
            Console.WriteLine($"\nPublish result:\n {publish.HttpStatusCode.ToString()}");
        }

        // Method to get SSO credentials from the information in the shared config file
        static AWSCredentials LoadSsoCredentials(string profile)
        {
            var chain = new CredentialProfileStoreChain();
            if (!chain.TryGetAWSCredentials(profile, out var credentials))
                throw new Exception($"Failed to find the {profile} profile");
            return credentials;
        }
    }

    // Class to read the caller's identity
    public static class Extensions
    {
        public static async Task<string> GetCallerIdentityArn(this IAmazonSecurityTokenService stsClient)
        {
            var arn = await stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest());
            return arn.Arn;
        }
    }
}

Run the application

  1. Using the AWS Management Console, login to your account and choose the region for which the local AWS credentials are configured.
  2. Navigate to the AWS IoT console, in the left menu, choose Test and then choose MQTT test client.

AWS IoT Console menu

  1. In the **Subscribe to a topic ** tab, enter the topicNameto subscribe to the topic on which your device publishes. Continuing with this example, on the Subscribe to a topic tab, in the Topic filter field, enter test/topic, and then choose Subscribe.

Subscribe to a topic

  1. In your IDE or development environment navigate to the .NET project folder AWSIoTPublish and run the following command:
dotnet run
  1. In the AWS IoT Console, check to see if your message came through.

Cleanup

While performing this tutorial, you created some resources that you can choose to clean up at this time.

  • There were no AWS resources created so there is nothing to clean up in the AWS Console.
  • If you don't want to keep your .NET project, remove the AWSIoTPublish folder from your development environment.
AWS
EXPERT
published 6 months ago1534 views