Jeff
Jeff

Reputation: 21

How to deploy a decoupled web application built with .NET Core (.NET 6) for Backend and vanilla html & javascript for Frontend to Azure?

I've built a simple web app using .Net Core (.Net 6) for the backend and vanilla html & javascript in a single "index.html" file in VS Code for the frontend. I've tested it on my local and everything works as intended.

I'm trying now to deploy it to Azure. I've deployed the backend successfully, but I'm not sure how to deploy the frontend. I know how to sign into Azure through VS Code and how to upload my "index.html" to Azure, but I don't know how to make the two parts work together in Azure. I also don't know if I should upload the index.html file into the same app service or a separate one.

I've searched here on Stack and also on the general Internet a lot for some info on this. Through this search, I've found basically two methods to do this. One is to upload the index.html as a "static" file and then make it communicate with my backend using Azure Messaging Service. The second is to use Docker to create a container that houses both the frontend and the backend and upload the container to Azure.

I would like to get some advice please?

Upvotes: 0

Views: 64

Answers (1)

Vivek Vaibhav Shandilya
Vivek Vaibhav Shandilya

Reputation: 2636

You can deploy your HTML file to static web app and can communicate the backend using API method.

Use fetch to fetch data from backend.

Below are the simple code for my backend webapp and HTML static webapp.

My Backend code :- HomeController.cs Its fetching the data from Api https://api.zippopotam.us/us/33162 and returning the value in Json

using html.server.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace html.server.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly HttpClient _httpClient;

        public HomeController(ILogger<HomeController> logger, HttpClient httpClient)
        {
            _logger = logger;
            _httpClient = httpClient;
        }

        public async Task<IActionResult> Index()
        {
            var url = "https://api.zippopotam.us/us/33162";

            _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0");

            var response = await _httpClient.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsStringAsync();
                return Content(data, "application/json");
            }
            else
            {
                return StatusCode((int)response.StatusCode, $"Failed to fetch data from GitHub API.{(int)response.StatusCode}");
            }
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }

}

Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpClient();
builder.Services.AddControllersWithViews();

var app = builder.Build();


if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

My Static Web app : It will serve my HTML file

Prerequesites :

  • Github or Azure DevOps require.

To deploy html file follow the steps using Git:

  • Install Git
  • Put you html file in new folder.
  • Run this command to create repository and push the file
git init
git add .               # . to add all file
git commit -m "add Html file"
  • Install Azure Tools extension
  • Click on Azure Static web app and select Create Static Web App...

  • Type your Static web app name and your GitHub repo name whatever you want to keep it.
  • Select HTML from the option and keep all default for path (/)

I am using the url of my deployed webapp

Index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML-MVC</title>
</head>
<body>
    <div>
        <h1>Hi Vivek</h1>
        <button>Get Data</button>
        <div>
            <p> </p>
        </div>
    </div>
</body>
<script>
            {
                const button = document.querySelector("button")
                const para = document.querySelector("p")
        
                button.addEventListener('click',(e)=>{
                    fetch('https://webapp12aug.azurewebsites.net/').then(res=>res.json()).then(data=>{
                        para.innerHTML = `  <ul>
                                               <li>${data['post code']}</li>
                                                <li>${data.country}</li>
                                                <li>${data.places[0]['place name']}</li>
                                                <li>${data.places[0]['state']}</li>
                                            </ul>`
                    })
                })
            }
        </script>
</html>

To Allow CORS Azure : Add the url of the static web app in the CORS section of backend web app

Hard code in Porgram.cs

var  builder  =  WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll",
        builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyHeader()
                   .AllowAnyMethod();
        });
});

var  app  =  builder.Build();
app.UseCors("AllowAll");

OUTPUT:

backend data

Static Web App

Upvotes: 0

Related Questions