Deploy a .NET API to Azure. Create a SQL database and Serve your... | by Richard Peterson | Towards Data Science

This article is the fourth in a series dedicated to building a .NET API for the Angular Tour Of Heroes tutorial.
So far, we have:
Set up our environment.Built a MSSQL Docker container database for local development.Wrote a .NET API for the Angular Tour of Heroes app.
Set up our environment.
Built a MSSQL Docker container database for local development.
Wrote a .NET API for the Angular Tour of Heroes app.
You can pull a working local development version of the Angular App, .NET API, and a Docker MSSQL database from my GitHub repo, or build it yourself by following the previous article in this series.
Now, let’s deploy our .NET API to Azure! I must give credit to this awesome Microsoft tutorial that goes into great detail about this process.
Set up environmentCreate Azure SQL serverDeploy .NET API to Azure
Set up environment
Create Azure SQL server
Deploy .NET API to Azure
You will need two crucial pieces of software:
The Azure Command Line Interface.NET Core — I am using version 3.0.2
The Azure Command Line Interface
.NET Core — I am using version 3.0.2
When these have been installed, pull the local version of the .NET API from my GitHub repo. Navigate to the Heroes.API directory from the command line and run the .NET Core program by running dotnet run. Once you confirm it runs on your system, stop the program.
Since you downloaded the project from GitHub, it came with a .git hidden folder, which we will need to remove. Go up one level from Heroes.API so that you can see all 3 folders that comprise the total app. Show the hidden folder .git folder and delete or run sudo rm -r .git from a linux or mac system.
Then, navigate back to the Heroes.API directory by typing cd Heroes.API. Run ls to make sure you see all the folders you expected.
We need to initialize a new git repository that we will push to an Azure remote repository. Run this from the Heroes.API directory:
git init git add . git commit -m "first commit"
Login to the Azure CLI by running az login.
Create a Resource Group named HeroesAPIgroup to house your resources with az group command.
az group create --name HeroesAPIgroup --location eastus
Create a SQL server in your resource group name heroesSQLdb by running
az sql server create \--name heroapisqlserver \--resource-group HeroesAPIgroup \--location eastus \--admin-user sqlAdmin \--admin-password Mystrongpassw0rd
You will get a JSON output of the deployment details when complete.
Configure a firewall for your server by running:
az sql server firewall-rule create \--resource-group HeroesAPIgroup \--server heroapisqlserver  \--name AllowAllIps \--start-ip-address 0.0.0.0 \--end-ip-address 0.0.0.0
Create a heroes database on your newly created SQL server.
az sql db create \--resource-group HeroesAPIgroup \--server heroapisqlserver   \--name heroes \--service-objective S0
To add a table to your heroes database, we will need to login to the Azure portal and find your HeroesAPIgroup Resource Group, and click on your heroes SQL database.
Go to the Query Editor and attempt to enter your SQL database using the username and password from when you created the SQL server. It should fail as your local IP address has not been given access to the server, per your firewall rule.
Go back to your heroes database overview. Click on Set server firewall.
From the firewall settings, click on Add Client IP. Now, you should be able to access the SQL server from your home or office IP address location.
Now, enter the SQL database using your username and password from the Query Editor.
When you are logged into the SQL Server, run the below query to add a table and insert sample data into the database.
CREATE TABLE HeroValue( id int, name VARCHAR(50) );INSERT INTO HeroValue (id, name)VALUES (1, 'Wonder Woman'), (2, 'Spiderman'), (3, 'Black Widow'), (4, 'Batman'), (5, 'Captain Marvel');
We have a database! Let’s copy out the connection string for use later. From Overview, click on Connection Strings, and copy the .NET connection string provided. Mine looked like this:
Server=tcp:heroapisqlserver.database.windows.net,1433;Initial Catalog=heroes;Persist Security Info=False;User ID=sqlAdmin;Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
Replace {your_password} with the password you chose for the admin.
We are not going to insert this connection string into our app. Once we have deployed the app, we are going to configure a connection for the app using az webapp config, which will take precedence over the connection string in appsettings.json. We will create this app-level connection string after we create the web app, so hang on to that connection string.
Let’s deploy that app!
We will need to configure a deployment user with authorization to push git repositories to Azure. Create a user now:
az webapp deployment user set \--user-name DeploymentUser420 \--password DeploymentPassw0rd!
You will get JSON output if this is successful. If you get errors, the Azure docs say: If you get a 'Conflict'. Details: 409 error, change the username. If you get a 'Bad Request'. Details: 400 error, use a stronger password.
The app service plan will determine the size of the virtual machine that is created to run your app. We will use the free linux tier of the app service plan.
az appservice plan create \--name HeroesAPIserviceplan \--resource-group HeroesAPIgroup \--is-linux \--sku FREE
Create a web app that will operate within the terms of your app service plan.
First, we need to check what runtimes are available. Run:
az webapp list-runtimes --linux
Choose the DOTNET| runtime that will work for your code. We are going with “DOTNETCORE|3.0”. Create the web app with the az webapp create command. I highly recommend reading the Azure docs on this versatile command.
az webapp create \--resource-group HeroesAPIgroup \--plan HeroesAPIserviceplan \--name heroes-api \--runtime "DOTNETCORE|3.0" \--deployment-local-git
The first thing you will see when the app has been created is the URL for the git remote. It is very important you save this! We will need this URL to push your local git repository to Azure.
My git repo URL. (Don’t worry this project will be deleted before publishing the article).
Local git is configured with url of 'https://DeploymentUser420@heroes-api.scm.azurewebsites.net/heroes-api.git'
Remember that connection string from we saved after setting up the SQL server? We will now use it to set a connection string at the app level. This will take precedence over the current connection string which points to a local docker mssql database. Don’t forget to replace {your_strong_password} with the password for your Admin.
az webapp config connection-string set \--resource-group HeroesAPIgroup \--name heroes-api \--settings MyDbConnection="Server=tcp:heroapisqlserver.database.windows.net,1433;Initial Catalog=heroes;Persist Security Info=False;User ID=sqlAdmin;Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" \--connection-string-type SQLServer
We need to set an environment variable so that our .NET API knows to connect to an Azure SQL database when it is in a Production environment, rather than the local docker database used for development.
az webapp config appsettings set \--name heroes-api \--resource-group HeroesAPIgroup \--settings ASPNETCORE_ENVIRONMENT="Production"
Now, we need to make some changes to our code in the .NET API to read the environment variable, and choose the Azure database or the Docker database accordingly.
Modify ConfigureServices in Startup.cs to first look for the environment variable ASPNETCORE_ENVIRONMENT, and lacking that variable, choose the local Docker database.
// Use SQL Database if in Azure, otherwise, use SQLiteif(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Production")    services.AddDbContext<HeroesContext>(options =>        options.UseSqlServer(            Configuration.GetConnectionString("MyDbConnection")));else    services.AddDbContext<HeroesContext>(options =>        options.UseSqlServer(            Configuration.GetConnectionString("DockerDB")));
Save your changes, and don’t forget to commit the git repo.
git add .git commit -m "connect to SQLDB in Azure"
Your app is ready for production deployment. Let’s push our git repository to the remote Azure repository that our web app is looking at for providing code. Add the git repo URL that we saved after we created the web app.
git remote add azure <deploymentLocalGitUrl-from-create-step>
Push your git repo to the Azure remote repo to deploy your app. When you run the below command, it will ask you for credentials. Enter the password for the deployment user we created, not your Azure login!
git push azure master
You did it! You deployed your app! Now let’s test it out. Browse to the heroes-api App Service Overview and copy the API URL endpoint. It should look something like this:
https://heroes-api.azurewebsites.net
Send a GET request to https://heroes-api.azurewebsites.net/api/Heroes, and observe the JSON output of all the pre-loaded heroes! Success!
Open the Tour of Heroes app and go to src/app/hero.service.ts.
Under the HeroService class, comment out the URL to the local .NET API, and replace localhost:5000 with the API URL endpoint from Azure. Your connection string will look like this:
private heroesUrl = ‘https://heroes-api.azurewebsites.net/api/Heroes';
Launch your angular app by running:
ng serve --open
You did it! You have a Frontend, Backend, and a database!
To deploy your Angular app to Azure, you can jump to my article!
Make sure you remember to swap out the connection string in HeroService.
Thank you for reading this far! I hope this article makes it easy for you to deploy to Azure, and if you need more explanation, this Azure tutorial really goes into detail!