0% found this document useful (0 votes)
13 views

Building an Amazon ECS Service with an ASP.NET Website_

This document outlines a hands-on exercise to build an Amazon ECS service named WeatherSite, which includes an ASP.NET website and a .NET Web API that retrieves weather data from an Amazon DynamoDB table. The activity involves setting up an AWS environment, creating a DynamoDB table, developing a Web API, and deploying both the API and website to Amazon ECS using AWS Fargate. The exercise concludes with testing the services in the cloud and updating the DynamoDB table before deleting the AWS resources.

Uploaded by

sskbn9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Building an Amazon ECS Service with an ASP.NET Website_

This document outlines a hands-on exercise to build an Amazon ECS service named WeatherSite, which includes an ASP.NET website and a .NET Web API that retrieves weather data from an Amazon DynamoDB table. The activity involves setting up an AWS environment, creating a DynamoDB table, developing a Web API, and deploying both the API and website to Amazon ECS using AWS Fargate. The exercise concludes with testing the services in the cloud and updating the DynamoDB table before deleting the AWS resources.

Uploaded by

sskbn9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Activity: Building an Amazon ECS Service with an ASP.

NET
Website

Overview
In this hands-on exercise, you will create an Amazon Elastic Container Service (Amazon ECS) service named
WeatherSite that consists of an ASP.NET website and a .NET Web API. The API will use an Amazon DynamoDB table to
retrieve weather data. The API will be deployed to an Amazon ECS service and the website to another Amazon ECS
service.

You can perform this lab on your local machine using Windows, MacOS, or Linux.

Duration
90 minutes

Here is what you will do


• You will begin by creating a DynamoDB table with some weather data. Next, you will create a .NET Web API
project that retrieves data from the table.
• After testing the Web API locally, you will deploy it and create an Amazon ECS service on AWS Fargate using
the AWS deployment tool for .NET CLI. Then, you will create an ASP.NET web site that accesses the API.
• After testing the web site locally, you will create another Amazon ECS service on Fargate using the AWS
deployment tool for .NET CLI.
• You will test your Amazon ECS service in the cloud by accessing the website, confirming data is retrieved from
the API, and monitoring activity in the AWS console.
• You will add data to the DynamoDB table, add another city to the website, and deploy the updates.
• Finally, you will delete your AWS resources.

1 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

2 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Section 1: Set up an AWS environment


In this section, you will set up your AWS environment.
1. Obtain an AWS account. Do not use a Production account.
2. Sign in to the AWS Management Console and choose an AWS Region to work in that supports Amazon ECS on
Fargate and supports DynamoDB.

3 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Section 2: Set up the development environment


In this section, you will install software to set up a development environment. Skip over items you already have
installed.
1. Install the AWS Command Line Interface (AWS CLI).
2. Configure the AWS CLI so it is linked to a user in your AWS account.
3. From a command or terminal window, configure your credentials and default Region with the following
command:

aws configure

4. Give your AWS user the permissions needed to deploy applications to Amazon ECS.
a. In the AWS Management Console, navigate to IAM.
b. Go to Users and choose your AWS user.
c. Choose Add permissions, then choose Attach existing policies directly.
d. Search for and select the check box for each of the following policies:
• PowerUserAccess
• AWSCloudFormationFullAccess
• AmazonECS_FullAccessAmazonEC2ContainerRegistryFullAccess
• AmazonSSMFullAccess
• IAMFullAccess

5. Install the .NET 6 SDK.


• Local machine: If you are using your local machine, download and install the .NET 6 SDK for your
operating system.

6. Install the AWS Deploy tool for .NET CLI with the following command:

dotnet tool install -g aws.deploy.tools

7. Install an integrated development environment (IDE), such as Microsoft Visual Studio 2022 (Windows), or
Visual Studio Code or JetBrains Rider (Linux, macOS, Windows). Ensure that you have installed the options or
extensions for .NET web development in C#.
8. If you are using Visual Studio, install and configure the AWS Toolkit. With the toolkit, you can examine your
AWS deployments within the IDE.
a. Download and Install

4 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

b. Configure
9. Install Docker Desktop, which must be running on your machine. If you already have Docker, be aware that you
need version 17.05 or later of the Docker Engine.

Check your work


In this section, you have done the following:
ü Installed all prerequisite software.
ü Configured the AWS CLI for your AWS user and AWS Region.
ü Configured the AWS Toolkit for your IDE.

5 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Section 3: Create an Amazon DynamoDB table


In this section, you will create a DynamoDB table named Weather and create some data records.
1. In a browser, sign in to the AWS Management Console.
2. At top right, set the Region you want to work in.
3. Navigate to Amazon DynamoDB and choose Create table.
a. For Table name, enter Weather.
b. For Partition key, enter Location.
c. For Sort key, enter Timestamp.
d. Choose Create table.
e. Wait for the table status to become Active.

4. Choose the Weather table name to get to its detail page, then choose Explore table items.
6 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

5. Add an item using the Form. You can also add items using the JSON view. See the Appendix for instructions.
a. Choose Create item and add an item with the following attributes: Location: Dallas, Timestamp: 2022-
07-23T06:00:00.
b. Choose Add new attribute to add attributes TempC (Number) 33, TempF (Number) 92, and Summary
(String) Hot.

c. Choose Create item to create the item.

6. Add more items using the JSON view. See the Appendix for instructions.

7 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

The completed table should have six items as listed in the following screenshot.

Check your work

You should now have the following:


ü A DynamoDB table named Weather
ü Table rows populated with data

8 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Section 4: Create WeatherAPI project


In this section, you will use the dotnet new command to create a .NET Web API project and update its code to retrieve
data from the DynamoDB table.
1. Generate a WebAPI project.
a. Open a command prompt or terminal window and change directory to a development folder.
b. Run the following dotnet new command to create a Web API project named WeatherAPI:

dotnet new webapi -n WeatherAPI

c. CD to the project folder.


d. Add the DynamoDB SDK package. Run the following dotnet add package command to add the
AWSSDK.DynamoDBv2 package to the project. You will need this library to communicate with the
Amazon DynamoDB service.

dotnet add package AWSSDK.DynamoDBv2

9 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

2. Open the WeatherAPI project in your IDE.


3. Select Region. If you have an AWS Toolkit installed for your IDE, select the same AWS Region you chose in
Section 1: Set up an AWS environment.
4. Disable HTTPS Redirection.
a. Open Program.cs in the code editor, and remove or comment out the following statement:

// app.UseHttpsRedirection();

5. Debug the project.


The generated project is a WeatherForecast API, commonly used in .NET samples.
a. To try it, do either of the following:
i. Press F5 in your IDE.
ii. Run dotnet run from the command line and browse to the endpoint address, with
/swagger/index.html at the end of the path.
b. In the browser tab that opens, you see a Swagger interface. Notice the service has a /WeatherForecast
action that returns mock weather data JSON. Test it by choosing GET, then Try it out, and then
Execute. Note the JSON response for each action.

You might or might not see a “Not secure” indicator about HTTPS in the browser, depending on
whether or not you accepted a local SSL certificate.

c. Stop the program from running.

10 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

6. Configure ports.
The Web API will run at port 8080 (HTTP) and 8443 (SSL).
a. Open Properties/LaunchSettings.json in the code editor.
b. On line 17, change the applicationUrl values to the following:

"applicationUrl": "https://localhost:8443;http://localhost:8080",

7. Code the data structure.


Open WeatherForecast.cs and replace it with the following code. This record structure matches the DynamoDB
items you created in Section 3: Create an Amazon DynamoDB table.
a. Copy and paste the following code into WeatherForecast.cs:

11 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

namespace WeatherAPI;

public class WeatherForecast


{
public string? Location { get; set; }

public DateTime Date { get; set; }

public int TemperatureC { get; set; }

public int TemperatureF { get; set; }

public string? Summary { get; set; }


}

8. Code the Weather Forecast Controller.


a. Open WeatherForecastController.cs in the Controllers folder, and replace (copy and paste) with the
following code.

b. On line 10, set RegionEndpoint to the AWS Region you are working in. For example,
RegionEndpoint.USEast1. This code implements a health check method at the root path of the service,
and a WeatherForecast method at /WeatherForecast.

The /WeatherForecast method takes a location parameter and retrieves data for it from the DynamoDB
Weather table. It performs a table scan to find records whose partition key matches the location.
Matching DynamoDB items are stored in a List of WeatherForecast objects. The results are returned as
an array of JSON records.

12 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DocumentModel;
using Microsoft.AspNetCore.Mvc;

namespace WeatherAPI.Controllers;

[ApiController]
[Route("")]
public class WeatherForecastController : ControllerBase
{
static readonly RegionEndpoint region = RegionEndpoint.USWest2; //ß Add your Region here

private readonly ILogger<WeatherForecastController> _logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger)


{
_logger = logger;
}

[HttpGet("")]
public string GetHealthcheck()
{
return "Healthcheck: Healthy";
}

[HttpGet("WeatherForecast")]
public async Task<IEnumerable<WeatherForecast>> GetWeatherForecast(string location =
"Dallas")
{
List<WeatherForecast> forecasts = new List<WeatherForecast>();

try
{
_logger.LogInformation($"00 enter GET, location = {location}");

var client = new AmazonDynamoDBClient(region);


Table table = Table.LoadTable(client, "Weather");

var filter = new ScanFilter();


filter.AddCondition("Location", ScanOperator.Equal, location);

var scanConfig = new ScanOperationConfig()


{
Filter = filter,
Select = SelectValues.SpecificAttributes,
AttributesToGet = new List<string> { "Location", "Timestamp", "TempC", "TempF", "Summary" }
};
13 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

_logger.LogInformation($"10 table.Scan");

Search search = table.Scan(scanConfig);

List<Document> matches;
do
{
_logger.LogInformation($"20 table.GetNextSetAsync");
matches = await search.GetNextSetAsync();
foreach (var match in matches)
{
forecasts.Add(new WeatherForecast
{
Location = Convert.ToString(match["Location"]),
Date = Convert.ToDateTime(match["Timestamp"]),
TemperatureC = Convert.ToInt32(match["TempC"]),
TemperatureF = Convert.ToInt32(match["TempF"]),
Summary = Convert.ToString(match["Summary"])
});
}
} while (!search.IsDone);

_logger.LogInformation($"30 exited results loop");

}
catch (Exception ex)
{
_logger.LogError(ex, "90 Exception");
}

_logger.LogInformation($"99 returning {forecasts.Count} results");

return forecasts.ToArray();
}
}

14 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

9. Save and Build.


a. Save your changes and ensure the project builds successfully.

Check your work

In this section, you have done the following:


ü Generated a WeatherAPI project.
ü Installed the AWSDK.DynamoDBv2 NuGet package.
ü Set WeatherForecastController.cs Region variable to your AWS Region.
ü Disabled HTTPS Redirection.
ü Updated WeatherForecast.cs with a structure that matches the DynamoDB items.
ü Updated WeatherForecastController.cs with a root healthcheck method and WeatherForecast method that
queries the DynamoDB weather table.

15 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Section 5: Test WeatherAPI locally


In this section, you will test the Web API locally and confirm data retrieval from DynamoDB.
1. Verify access to the application.
a. In your IDE, press F5 and wait for the app to build and launch in a browser. Or run dotnet run from the
command line and brose to http://localhost:8080/swagger/index.html.
b. In the Swagger page, you should now find your two GET methods and the WeatherForecast schema.

2. Test the healthcheck action.


a. In the browser, remove the Swagger path from the URL to hit the service root, and you should find a
health check message. AWS App Runner will regularly ping the site to check health.

3. Test WeatherForecast action.


a. Add /WeatherForecast?location=Dallas to the end of the URL path.
b. You should find weather forecast data JSON, with values you created in the DynamoDB table in
Section 3: Create an Amazon DynamoDB table.

16 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

4. Test another location.


a. Change the URL path to end in /WeatherForecast?location=Minneapolis.
b. Now you should find the data for that city.

5. Test an invalid location.


a. Try a different location name, and you should find an empty response because there is no data for it in
the table.

6. Stop testing.
a. Stop the program from running.

Check your work

In this section, you have done the following:


ü Tested the WeatherAPI locally.
ü Confirmed the WeatherAPI can retrieve data from the DynamoDB table.

17 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Section 6: Deploy WeatherAPI to Amazon ECS


In this section, you will containerize and deploy the WeatherAPI project to Amazon ECS using the AWS deployment
tool for .NET CLI.
1. Run the AWS deployment tool.
a. In a command prompt or terminal window, navigate to the WeatherAPI folder.
b. Run the following command:

dotnet aws deploy

Note: The following deployment will fail if you do not have the Node.js and Docker
dependencies installed on your local machine. In that case, follow the instructions for
installing them: Node.js and Docker.
c. If you are prompted to Select an existing AWS deployment target, select the choice for Deploy to a
new Cloud Application.
d. Select the choice for ASP.NET Core App to Amazon ECS using Fargate.

e. For name of new CloudFormation stack, press Enter to accept the default name of WeatherAPI.

18 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

2. Edit settings.
a. When Current settings are displayed, enter more to see advanced settings. A numbered list of settings
is displayed.
b. Enter 9 to select Elastic Load Balancer and respond to prompts as follows:
• Create New Load Balancer: y
• Deregistration delay: 60
• Health Check path: /
• Health Check Timeout: 5
• Health Check Interval: 30
• Healthy Threshold Count: 5
• Unhealthy Threshold Count: 2
• Internet-Facing: y

19 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

3. Deploy the project.


a. Press Enter to start deployment. The deployment will create a load balancer, three ECS tasks, and new
roles.

b. Wait while the service is containerized and deployed, which will take several minutes. When it
completes, note the deployment details at the end of the output.
c. Record the details under Application Endpoint. You will need the endpoint to test the service.
Endpoint URL:

20 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

4. Review Dockerfile.
In your project folder, notice that a Dockerfile file has been added. The AWS deployment tool created
this file and used it with Docker to containerize the project. The Dockerfile should look similar to the
following. You might see 6.0 or 7.0 depending on which version you are using.

FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base


WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build


WORKDIR /src
COPY ["WeatherAPI.csproj", ""]
RUN dotnet restore "WeatherAPI.csproj"
COPY . .
WORKDIR "/src/"
RUN dotnet build "WeatherAPI.csproj" -c Release -o /app/build

FROM build AS publish


RUN apt-get update -yq \
&& apt-get install curl gnupg -yq \
&& curl -sL https://deb.nodesource.com/setup_14.x | bash \
&& apt-get install nodejs -yq
RUN dotnet publish "WeatherAPI.csproj" -c Release -o /app/publish

FROM base AS final


WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WeatherAPI.dll"]

21 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

5. Review in the Amazon ECS console. Examine what’s been deployed in the AWS console.
a. In the AWS Management Console, navigate to Amazon ECS.
b. Choose Clusters from the navigation pane, and the WeatherAPI cluster should be listed in the content
pane. You should find one FARGATE service with three running tasks.
c. Choose the WeatherAPI cluster name to examine its detail.

22 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

d. In the content pane for WeatherAPI, explore the tabs to find what was deployed. You should find three
running tasks of launch type FARGATE.

6. Test the ECS endpoint.


a. Open another browser tab, and visit the endpoint URL you recorded earlier in Step 3c. You should see a
Healthy health check response. This test shows that the ECS-hosted service is responding.

Check your work

In this section, you have done the following:


ü Containerized and deployed the project to Amazon ECS with the AWS deployment tool for .NET CLI.
ü Confirmed the deployment in the Amazon ECS console.
ü Confirmed the base endpoint URL is returning a healthy health check.

23 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Section 7: Update ECS task role and test API


In this section, you will create an AWS Identity and Access Management (IAM) policy for DynamoDB access, update the
ECS task role permissions, and test the Amazon ECS service.
1. Test API and note missing permission.
a. In a browser, visit the endpoint URL with /WeatherForecast?location=Dallas added to the end of the
path.
b. You should notice that no data is returned. This is because the ECS task role that is running the
WeatherAPI service does not have permissions to access the DynamoDB Weather table. Keep this
browser open; you will return to it later in this section.
2. Create an IAM policy that allows access to the Weather DynamoDB table.
a. In the AWS Management Console, navigate to IAM.
b. Choose Policies from the navigation pane, and then choose Create policy.

c. Create the policy and enter (copy and paste) the following JSON. Replace [account] with your 12-digit
AWS account number, and [region] with your AWS Region (for example: us-west-2).

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Action": "dynamodb:*",
"Resource": "arn:aws:dynamodb:[region]:[account]:table/Weather"
}
]
}

24 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

e. Choose Next: Tags and then Next: Review.


f. Name the policy ddb-weather and choose Create policy.
3. Modify the task role. The Amazon ECS service doesn’t yet have permissions to access the Weather DynamoDB
table. Update the role to add two policies.
a. In the Amazon ECS console, choose the WeatherAPI cluster to view its detail.
b. Choose WeatherAPI-service to examine the service configuration.

25 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

c. Choose the Configuration and tasks tab, and then choose the Task definition link.

d. Choose the Task role link. This takes you to the Role definition in the IAM console.

26 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

e. Choose Add permissions, and then choose Attach policies.

f. Search for and select the ddb-weather permission. Choose Attach policies.

g. Search for and select the AmazonDynamoDBFullAccess permission.

27 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

h. Choose Attach policies.


i. You should now have both policies attached to the role as listed in the following screenshot.

4. Re-test the API.


a. Refresh the page that returned no results in Step 1b. This time, you should find the JSON data
returned. The IAM role update provided access to the DynamoDB table.

Check your work

In this section, you have done the following:


ü Tested the WeatherAPI ECS service.
ü Created a policy named ddb-weather.
ü Updated the Amazon ECS task role with new permissions for DynamoDB.
ü Re-tested the WeatherAPI Amazon ECS service and had data returned successfully.

28 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Section 8: Create WeatherSite project


In this section, you will use the dotnet new command to create a .NET web project and update its code to retrieve data
from the DynamoDB table.
1. Generate a web project.
a. Open a command prompt or terminal window and navigate to a development folder.
b. Run the following dotnet new command to create a new Web API project named WeatherSite.

dotnet new webapp -n WeatherSite

c. Navigate to the WeatherSite project folder.


d. Run the following dotnet add package command to add the System.Net.Http package to the project. You
will need this library to communicate with the WeatherAPI service.

dotnet add package System.Net.Http

2. Open the project in the IDE.


a. Open the WeatherSite project in your IDE.
3. Disable HTTPS Redirection.
a. Open Program.cs in the code editor and remove or comment out the following statement:

// app.UseHttpsRedirection();

4. Debug the project. The generated project is a simple web application, commonly used in .NET samples.
a. To try it, do either of the following:
i. Press F5 in your IDE.
ii. Run dotnet run from the command line and browse to the endpoint address, with
http://localhost:<port>.

29 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

b. In the browser tab that opens, there is a simple page with a welcome message.

c. Stop the program from running.

5. Add the WeatherAPI configuration setting.


a. Open appsettings.json in the code editor and replace (copy and paste) with the code below, replacing
[service-address] with the endpoint address of the WeatherAPI ECS service. Note: This is the
WeatherAPI service URL from Section 6. It should not have a trailing slash.

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"AppSettings": {
"WeatherAPI": "http://[service-address]"
}
}

30 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

6. Configure ports. The Web site will run at port 80 (HTTP) and 443 (SSL), but you might not be able to use those
ports locally. If your local development machine is running a local web server such as IIS Express, they might
not be available. For now, use ports 8080 and 8443.
a. Open Properties/LaunchSettings.json in the code editor.
b. On line 17, change the applicationUrl values to the following:

"applicationUrl": "https://localhost:8443;http://localhost:8080",

7. Code the WeatherSite record structure. Add file WeatherForecast.cs to the project with the following code. This
record structure matches the items returned by the Weather API.

namespace WeatherSite;

public class WeatherForecast


{
public string? Location { get; set; }

public DateTime Date { get; set; }

public int TemperatureC { get; set; }

public int TemperatureF { get; set; }

public string? Summary { get; set; }


}

8. Code the service client.


a. Open WeatherSite/Pages/Index.cshtml.cs in the code editor and replace (copy and paste) with the
following code.
This is the code-behind file for the Razor page Index.cshtml. The URL for the WeatherAPI service is read
from a setting in appSettings.json. The /WeatherForecast route takes a location parameter and
retrieves data for it from the DynamoDB Weather table. The results are returned as an array of JSON
records.

31 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace WeatherSite.Pages;

public class IndexModel : PageModel


{
public string Location { get; set; }
public WeatherForecast[] Items { get; set; }
public string Message { get; set; }

private readonly ILogger<IndexModel> _logger;

public IndexModel(ILogger<IndexModel> logger)


{
_logger = logger;
}

public async Task OnGet()


{
try
{
var apiUrl = new
ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("AppSett
ings")["WeatherAPI"];
Location = Request.Query["location"].FirstOrDefault() ?? "Dallas";
var client = new HttpClient() { BaseAddress = new Uri(apiUrl) };
var response = await
client.GetAsync($"WeatherForecast?location={Location}");
response.EnsureSuccessStatusCode();
var items = await
response.Content.ReadFromJsonAsync<WeatherForecast[]>();
Items = items;
Message = $"{Items.Count()} forecast records found ";
}
catch(HttpRequestException ex)
{
Message = ex.Message;
}
}
}

9. Code the page.


a. Open WeatherSite/Pages/Index.cshtml in the code editor, and replace (copy and paste) with the
following code.
The Razor page displays some values from the code-behind model using @ notation: location,
success/error message, and a table of weather forecast data.

32 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}

<style>
.styled-table {
border-collapse: collapse;
font-size: 0.9em;
font-family: sans-serif;
min-width: 400px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
margin-left: auto;
margin-right: auto;
}

.styled-table thead tr {
background-color: cornflowerblue;
color: #ffffff;
text-align: left;
}

.styled-table th,
.styled-table td {
padding: 12px 15px;
}

.styled-table tbody tr {
border-bottom: 1px solid #dddddd;
}

.styled-table tbody tr:nth-of-type(even) {


background-color: #f3f3f3;
}

.styled-table tbody tr:last-of-type {


border-bottom: 2px solid cornflowerblue;
}

.styled-table tbody tr.active-row {


font-weight: bold;
color: cornflowerblue;
}

</style>

33 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

<div class="text-center">
<h1 class="display-4">@Model.Location Weather</h1>
<p>Weather Forecast</p>
<p>@Model.Message</p>

<p><a href="/?location=Dallas">Dallas</a></p>
<p><a href="/?location=Minneapolis">Minneapolis</a></p>

@if (@Model.Items != null)


{
<table class="styled-table">
<thead>
<tr><th>Location</th><th>Time</th><th>Temp (°C)</th><th>Temp
(°F)</th><th>Summary</th>
</thead>
<tbody>
@foreach (var forecast in Model.Items)
{

<tr><td>@forecast.Location</td><td>@forecast.Date.ToString("yyyy-MM-dd
HH:MM")</td><td>@forecast.TemperatureC</td><td>@forecast.TemperatureF</td><td>@for
ecast.Summary</td></tr>
}
</tbody>
</table>
}
</div>

10. Save and build.


a. Save your changes and ensure the project builds successfully.

At this point, you have created all the components for the architecture:
database table, API, and website.

34 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

35 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Check your work

After completing this section, you have done the following:


ü Generated the WeatherSite project.
ü Disabled HTTPS Redirection.
ü Debugged the project.
ü Added the WeatherAPI to the configuration settings.
ü Configured HTTP ports.
ü Updated WeatherForecast.cs with a record structure that matches the DynamoDB items.
ü Coded the service client.
ü Coded the web page.

36 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Section 9: Test WeatherSite locally


In this section, you' will test the web site locally and confirm that it can communicate with the Weather table.
1. Debug the project.
a. In your IDE, press F5 and wait for the web app to build and launch in a browser. The website should
load and display weather data for Dallas.

Note: If you are using Visual Studio, set WeatherSite as the startup project before starting the
debugger.

2. Choose the Minneapolis link. The page should refresh with data for that city.

3. Stop debugging. Stop the WeatherSite debugger in your IDE.

37 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

4. Optional: Configure production ports. Perform this step only if you have access to 80 and 443 to use as
production ports for the web site.
a. In the IDE with the WeatherSite project open, open Properties/LaunchSettings.json in the code editor.
b. On line 17, change the applicationUrl values as follows:

"applicationUrl": "https://localhost:443;http://localhost:80",

c. Save your changes and confirm the project builds successfully.

Check your work

After completing this section, you have done the following:

✓ Tested the WeatherSite project locally.

✓ Confirmed data is retrieved from the WeatherAPI backend Amazon ECS service.

38 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Section 10: Deploy WeatherSite to Amazon ECS


In this section, you will containerize and deploy the WeatherSite project to Amazon ECS using the AWS deploy tool for
.NET CLI. This is similar to Section 6: Deploy WeatherAPI to Amazon ECS, but this time you deploy the frontend
website.
1. Run the AWS deployment tool.
a. In a command prompt or terminal window, navigate to the WeatherSite folder.
b. Run the dotnet aws deploy command:
dotnet aws deploy
c. If prompted to select a new or existing deployment, choose Deploy to a new Cloud Application.
d. Select the choice for ASP.NET Core App to Amazon ECS using Fargate.

e. For name of new CloudFormation stack, press Enter to accept the default name of WeatherSite.

39 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

2. Edit settings.
a. When Current settings are displayed, enter more to list the advanced settings. A numbered list of
settings is displayed. Enter 9 to select Elastic Load Balancer and respond to prompts as follows:
• Create New Load Balancer: y
• Deregistration delay: 60
• Health Check path: /
• Health Check Timeout: 5
• Health Check Interval: 30
• Healthy Threshold Count: 5
• Unhealthy Threshold Count: 2
• Internet-Facing: y

40 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

3. Deploy the WeatherSite project.


a. Press Enter to start deployment. The deployment will create a load balancer, three ECS tasks, and new
roles.

b. Wait while the website is containerized and deployed, which will take several minutes. When it
completes, note the deployment details at the end of the output.

Record the details under Application Endpoint. You will need endpoint to test the website.
Endpoint URL:

41 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

4. Review Dockerfile. In your project folder, notice that a Dockerfile file has been added. The AWS
deployment tool created this and used it with Docker to containerize the project. The Dockerfile should
look similar to the following. You might see 6.0 or 7.0 depending on which version you are using.

FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base


WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build


WORKDIR /src
COPY ["WeatherSite.csproj", ""]
RUN dotnet restore "WeatherSite.csproj"
COPY . .
WORKDIR "/src/"
RUN dotnet build "WeatherSite.csproj" -c Release -o /app/build

FROM build AS publish


RUN apt-get update -yq \
&& apt-get install curl gnupg -yq \
&& curl -sL https://deb.nodesource.com/setup_14.x | bash \
&& apt-get install nodejs -yq
RUN dotnet publish "WeatherSite.csproj" -c Release -o /app/publish

FROM base AS final


WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WeatherSite.dll"]

42 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

5. Review in the Amazon ECS console. Examine what’s been deployed in the AWS console:
a. In the Amazon ECS console, navigate to ECS.
b. Select Clusters from the navigation pane. The WeatherSite cluster should be listed. There should be
one FARGATE service with three running tasks.

c. Choose the WeatherSite cluster name to view its detail. Explore the tabs to see what was deployed.
6. Test the ECS endpoint.
a. In another browser tab, visit the endpoint URL you recorded earlier in Step 3b. The website should
display, defaulting to location Dallas.

b. Choose the link for Minneapolis, to display the data for that locale.
43 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Congratulations, you have created a DynamoDB table and a website and API hosted in Amazon ECS on Fargate.

Check your work

You should now have done the following:


ü Containerized and deployed the website to Amazon ECS with the AWS deployment tool for .NET CLI.
ü Confirmed deployment in the Amazon ECS console.
ü Confirmed the website is live and able to access the Weather API service.
ü Verified that the website, API, and DynamoDB table work together on AWS.

44 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Section 11: Deploy an Update


In this section, you will add more data to your DynamoDB table, update the website with a third location, and deploy
the updated website. You will also change the task count from 3 to 2.
1. Add data for another location to the DynamoDB weather table.
a. In the AWS Management Console, navigate to DynamoDB, then Tables, and choose the Weather table.
b. Choose Explore table items. Add three more items for a new location such as Seattle or a location of
your choosing, just as you did earlier in Section 3: Create an Amazon DynamoDB table.

2. Update the website for the new location.


a. Open the WeatherSite project in your IDE.
b. Open Pages/Index.cshtml in the code editor, and insert the following code after the link for
Minneapolis:

<p><a href="/?location=Seattle">Seattle</a></p>

c. Save your changes and build the project.


3. Deploy an update.
a. Open a command prompt or terminal window and navigate to the WeatherSite project folder.
b. Run the command dotnet aws deploy to deploy an update:

dotnet aws deploy

45 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

c. Select the choice for WeatherSite (CloudFormation Stack) (default).

d. When Current settings are displayed, select 1. Desired Task Count and change it from 3 to 2.

46 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

e. Press Enter to begin the deployment, which will take a few minutes.

f. Wait for the update to complete. Notice the endpoint for the Amazon ECS service has not changed,
because this is an update.

4. Confirm task count change in the Amazon ECS console. Navigate to Amazon ECS and choose Clusters. Your
WeatherSite task count, previously 3, should now be 2.

47 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

5. Test the updated website.


a. In a browser, visit your website at the same endpoint you used previously in Section 10, Step 3b.
Confirm the web page now shows the third location for Seattle.

b. Click the link for Seattle and confirm that the data changes.

48 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Check your work

In this section, you have done the following:


ü Added Seattle weather data to the DynamoDB table.
ü Updated the website project main page with a Seattle location link.
ü Deployed the updated website to Amazon ECS with a reduced task count.
ü Tested the updated website hosted in Amazon ECS.

49 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Section 12: Shut it down


When you're done with this exercise, follow these steps to deallocate the resources. You don't want to accrue AWS
charges for something you're no longer using.
1. Delete the deployment for WeatherSite.
a. In a command or terminal window, navigate to the WeatherSite project folder.
b. Run the command dotnet aws delete-deployment WeatherSite and confirm the deletion:

dotnet aws delete-deployment WeatherSite

c. Wait for the delete process to complete.


d. In the AWS Management Console, navigate to Amazon ECS and confirm that the WeatherSite cluster is no
longer listed.

2. Delete the deployment for WeatherAPI.


a. In a command or terminal window, navigate to the WeatherAPI project folder.
b. Run the command dotnet aws delete-deployment WeatherAPI and confirm the deletion.

dotnet aws delete-deployment WeatherAPI

c. In the AWS Management Console, confirm that the WeatherAPI cluster is no longer listed.

3. Delete the DynamoDB Weather table.


A. In the AWS Management Console, navigate to Amazon DynamoDB.
B. Choose the Weather table, and then choose Delete from the Actions menu.
C. Confirm the delete and wait for it to complete.

Check your work

You should now have done the following:


ü Deleted your two Amazon ECS deployments.
ü Deleted all other resources you manually allocated from the AWS Management Console.

50 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Summary
In this lab activity, you achieved the following:
1. You created a DynamoDB table and populated it with weather data.
2. You developed a .NET Web API project that retrieves weather data from the DynamoDB table.
3. You deployed the WeatherAPI project to Amazon ECS on Fargate, using the AWS deployment tool for .NET CLI.
4. You developed a website that retrieves data from WeatherAPI.
5. You deployed the WeatherSite project to Amazon ECS on Fargate, using the AWS deployment tool for .NET
CLI.
6. You updated weather data and the website and deployed the updated website to Amazon ECS and modified its
task count.
7. You deleted the deployments for WeatherSite and WeatherAPI, and deleted the Weather DynamoDB table in
the AWS console.

51 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

Appendix: Populate the Weather table using JSON

1. In the AWS Management Console, navigate to Amazon DynamoDB.


2. Choose the Weather table name to get to its detail page. Then choose Explore table items.
3. Add the table items.
a. Choose Create item and then select the JSON view.
b. Enter the following JSON code (Dallas, morning) and choose Create Item.

{
{
"S": "Dallas"
},
{

},
{
"S": "Hot"
},
{
"N": "33"
},
{
"N": "92"
}
}

52 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

c. In the same way, add the second item (Dallas, mid-day) with the following JSON.

{
{
"S": "Dallas"
},
{

},
{
"S": "Scorching"
},
{
"N": "43"
},
{
"N": "109"
}
}

53 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

d. Add the third item (Dallas, evening) with the following JSON.

{
{
"S": "Dallas"
},
{

},
{
"S": "Hot"
},
{
"N": "36"
},
{
"N": "97"
}
}

e. Add the fourth item (Minnesota, morning) with the following JSON.

{
{
"S": "Minneapolis"
},
{

},
{
"S": "Cool"
},
{
"N": "13"
},
{
"N": "56"
}
}

54 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

f. Add the fifth item (Minnesota, mid-day) with the following JSON.

{
{
"S": "Minneapolis"
},
{

},
{
"S": "Balmy"
},
{
"N": "22"
},
{
"N": "72"
}
}

g. Add the sixth item (Minnesota, evening) with the following JSON.

{
{
"S": "Minneapolis"
},
{

},
{
"S": "Cool"
},
{
"N": "19"
},
{
"N": "67"
}
}

55 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Activity: Building an Amazon ECS Service with an ASP.NET
Website

4. Verify your Weather table items from the DynamoDB console.

5. Optional: If you want, add more table items for your favorite locations.

56 © 2023, Amazon Web Services, Inc. or its affiliates. All rights reserved.

You might also like