Azure AppService and dotnetcore
Tags: azure, appservice, dotnet, csharp
Published: 2021-03-12 02:44:17

#Let us understand one of the popular services of Azure - Appservice with help of dotnetcore application.

Before going deep dive, these are few questions which needs to be answered - what is AppService? How can it be useful? what are the features available to use? Here's an overview of Appservice and its features. 

It's a platform as a service (Paas) made available by Azure to make it easier to deploy web applications (backend/frontend) with the help of easy to use UI driven service to host web applications, containerized applications and API applications. Fully managed service with infrastructure maintenance, built-in security, patching and scaling.

Alternative to web servers like IIS, Apache, Nginx to quickly 
build, deploy and scale web applications.

Supported Programming Languages are .Net, .Netcore, Node.js, Java, Python and PHP.

Different price plans are available to choose from depending on the application requirements. please find more details on pricing [here](https://azure.microsoft.com/en-in/pricing/details/app-service/windows/).

One of the exciting feature of appservice is deployment slots. You can create slots to differentiate dev, qa, staging and prod environments. These slots can also be swapped to make staging to prod and prod to staging easier with a click. This is a useful scenario when a new feature of your application is ready to be deployed to prod, staging slot can be created and validated by your team before swapping it with prod slot.

we will learn how to use appservice by creating a simple frontend application using dotnetcore razor which displays weather information by calling a backend web api service created using dotnetcore webapi, both hosted in appservice.

Hope you already have basic overview on dotnetcore. More details on dotnetcore are available [here](https://www.c-sharpcorner.com/article/getting-started-with-net-core-3-1-part-one/).  

Follow the below dotnet commands to create web application
1.Create a frontend application based on razor.
```
dotnet new razor -n frontend
```
2.Create a backend webapi application. dotnet provides us with default WeatherForecast API to get random weather details.
```
dotnet new webapi -n backend
```
3.Create solution file and add both frontend and backend applications.
```
dotnet new sln
dotnet sln add frontend backend
```

Once both the applications are created, let us proceed further from visual studio. If visual studio 2019 is not installed, follow the instructions provided [here](https://docs.microsoft.com/en-us/visualstudio/install/create-an-offline-installation-of-visual-studio?view=vs-2019). Solution should have both frontend and backend applications as shown below.
![SolutionExplorer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/47x6a643ix750v82m4pj.PNG)

##Integrate frontend application to use backend service

1.Create a class WeatherForecast.cs to represent WeatherForecast information.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace frontend
{
    public class WeatherForecast
    {
        public DateTime Date { get; set; }

        public int TemperatureC { get; set; }

        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

        public string Summary { get; set; }
    }
}
```

2.Add WeatherClient.cs class to frontend application which includes code to call backend application and return back weather details.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace frontend
{
    public class WeatherClient
    {
        private readonly JsonSerializerOptions options = new JsonSerializerOptions()
        {
            PropertyNameCaseInsensitive = true,
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        };

        private readonly HttpClient httpClient;
        
        public WeatherClient(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        public async Task<WeatherForecast[]> GetWeathersAsync()
        {
            var responseMessage = await this.httpClient.GetAsync("/weatherforecast");
            var stream = await responseMessage.Content.ReadAsStreamAsync();
            return await JsonSerializer.DeserializeAsync<WeatherForecast[]>(stream, options);
        }
    }
}

```

3.Configure backend client in startup class.
```
....
 // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();

            services.AddHttpClient<WeatherClient>(httpClient =>
            {
              //include the backend application url once it is deployed to appservice
                httpClient.BaseAddress = new Uri("url of backedn application");
            });
        }
....
```

4.Add Forecasts property to index.cshtml.cs file. This property is used to fill in the ui.
```
....
public WeatherForecast[] Forecasts { get; set; }
....
```
Change OnGet Method in index.cshtml.cs file to call backend service and store the result in Forecasts property.
```
....
 public async Task OnGet([FromServices]WeatherClient weatherClient)
 {
     Forecasts = await weatherClient.GetWeathersAsync();
 }
....
```
5.Modify Index.cshtml razor page to render Forecast property information.
```
@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

Weather Forecast:

<table class="table">
    <thead>
        <tr>
            <th>Date</th>
            <th>Temp. (c)</th>
            <th>Temp. (f)</th>
            <th>Summary</th>
        </tr>
    </thead>
    <tbody>
        @foreach(var forecast in @Model.Forecasts)
        {
            <tr>
                <td>
                    @forecast.Date.ToShortDateString()
                </td>
                <td>
                    @forecast.TemperatureC
                </td>
                <td>
                    @forecast.TemperatureF
                </td>
                <td>
                    @forecast.Summary
                </td>
            </tr>
        }
    </tbody>
</table>
```

To test backend application, run the application with IISExpress in Visual Studio and navigate to /WeatherForecast in browser.
![Backend API Localhost](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7klcaxczpww67bd1ya71.PNG)

To test frontend application, run the application with IISExpress in Visual Studio, application will redirect to browser with localhost url.
![Fronend UI App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w6whhvedoik3jda4epy0.PNG)

##Deploy applications to AppService

###Create frontend and backend web apps
Navigate to [Azure Portal](https://portal.azure.com)
1. Create webapp for backend application from Azure portal and provide below information
   * ResourceGroup: Select existing one or create a new one with unique name across your azure account.
   * Name: Provide globally unique name for azure web app in azure.
   * Runtime Stack: Select .Net Core 3.1.
   * Region: Select any of the regions from dropdown.
   * Windows Plan: Select existing appservice or create a new plan.
   * Sku and Size: Select Free F1 plan to avoid incurring costs.
Click on Review+create and create.
   ![BackEnd WebApp](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c4z46l5lo0f07i6ahate.png)
2. Create webapp for frontend application from Azure portal and provide below information
   * ResourceGroup: Select existing one or create a new one with unique name across your azure account.
   * Name: Provide globally unique name for azure web app in azure.
   * Runtime Stack: Select .Net Core 3.1.
   * Region: Select any of the regions from dropdown.
   * Windows Plan: Select existing appservice or create a new plan.
   * Sku and Size: Select Free F1 plan to avoid incurring costs.
Click on Review+create and create.
![Front End Web App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ium7ibipg4fq2pj3t5q8.png)

###Publish backend application to azure appservice webapp created above
1.To deploy application to appservice, visual studio provides option to publish. Right click on backend application and select publish.
![publish window](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v09nwlc9enf0z70340g0.PNG)
2.If you dont see any options, click on start.
![No Publish Profiles](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tao9g6zgzq5yq10nklkt.PNG)
3.Select Azure Target.
![Azure Target](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1l6anu6jswhxyd82jlr3.PNG)
4.Select Azure App Service (Windows) option in next tab.
![Azure App Service windows](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ozancj77m6z887719ff.PNG)
5.Sign in to microsoft azure account to see the list of resources created. Select backendwebapp created.
![Backend webapp](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f2glzni2knyqlbxukkjx.png)
6.skip API Management setup and click on Finish
![Skip API Mgmt](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xa8y6lue30j5bwiy8rns.png)
7.Finally select publish option to deploy the backend web app to azure app service.
![Backend web app publish](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jzoml8l67smtvqu98afe.png)
8.Ensure publish output is successful.
![Backend webapp publish output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zxvey5v6qlaa3qriix7z.png)
9.Navigate to the Url mentioned in output by appending /WeatherForeCast at the end of Url to see the output from backend webapp.
![BackEndWebApp Url working](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2cspqew4uzwp9lnn16yl.png)

###Publish frontend application to azure appservice webapp created above
1.Follow the same steps for frontend application and publish the app to frontend webapp created above.
![FrontEndWebapp](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dxuv4m891wf0mbzwtuoo.png)
Publish Window.
![FrontEnd webapp publish window](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zbvku9c0rgomf8hylge8.png)
Output Window.
![FrontEnd webapp publish output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1fmjrw2t3ktp37fagrfm.png)
2.Navigate to the url mentioned in output window above
![FrontEnd WebApp url](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/39549ekm85874cz6cf12.png).

Azure Appservice provides in-browser editor to edit the applications files deployed. Navigate to development section under the backend webapp created in azure. Click on Go, you will be navigated to in-browser editor.
![Backend webapp development section](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/um34w6hs0leos7fr85wt.png)

Appservice Editor.
![AppService Editor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eag8wpf8312lt0pfb4p7.png)

To know more about deployment slots, container deployment, scaling appservice, head over to [microsoft learn](https://docs.microsoft.com/en-us/learn/paths/deploy-a-website-with-azure-app-service/).