AWS Developer Tools Blog

Run Blazor-based .NET Web applications on AWS Serverless

Blazor WebAssembly is a new client-side web development framework that lets developers to use C# to create application front end. Blazor can run client-side C# code directly in the browser, using WebAssembly. Blazor WebAssembly runs on .NET Core and it is an open source and cross-platform web framework for building single-page application using .NET and C# instead of traditional JavaScript. In this framework you implement Blazor UI components using .NET code and Razor syntax.

Web application developed using Blazor components can be hosted in two different ways. Firstly, Blazor can run directly in the client browser using WebAssembly and alternatively it can also run your client code on the server, where client event communicates to server using SignalR. In this post, you will explore the former approach. You will develop a web application interface using Blazor WebAssembly, which will run in the browser and deploy the same as static web site without any .NET server components. This blog for ASP.NET C# developers and shows steps to host a single page web application using Blazor WebAssembly to AWS, easily.

Overview of solution

In this post you will create a AWS serverless web application that will allow you to download and save any YouTube videos to your Amazon Simple Storage Service (Amazon S3) bucket. First you will set up the back end layer using Amazon API Gateway and AWS Lambda. We will use .Net Core 3.1 runtime to host AWS Lambda Code. Then you will create a web application interface, developed using Blazor WebAssembly which will be hosted as a static website with Amazon S3. This website will be accessed via Amazon CloudFront, which is a fast content delivery network (CDN) service that securely delivers static content. We will use Amazon API Gateway to post user request from the front end to the back-end layer.

Application Architecture

Architecture diagram

Prerequisites

For this walk through, you should have the following prerequisites:

This post implements the solution in Region us-east-1.

Source Code

Source code for the application back end  can be downloaded from GitHub repo. Once downloaded go ahead and build the solution within Visual Studio to make sure all references are up to date.

Setting up application back end

For this walk through you will be using YDownloader project. The deployment script already has been created using AWS SAM template (template.yaml), which will help you to deploy the back end infrastructure to AWS. But to deploy this AWS CloudFormation stack first you need to create a S3 bucket. Name the bucket as code-[your-unique-bucket-name]. Please make sure that your bucket should be in the same region where you plan to deploy your back end infrastructure which is us-east-1 in this scenario.

To complete set up, use the following steps:

  1. Navigate to the YDownloader folder and open command prompt (cmd) here.
  2. Open swagger.yaml file and replace text [your-aws-account-no] with your AWS account number.
  3. Run sam validate. Once the template been validated run below command to package the source code.sam package --template-file template.yaml --output-template-file sam.yaml --s3-bucket code-[your-unique-bucket-name]
  4. This should create a file name sam.yaml which will help us to deploy your application back end. After this run below command. This will create a CloudFormation stack name downloader and deploy AWS Lambda code to process and download your YouTube video and a AWS API Gateway endpoint with AWS Lambda integration.sam deploy --template-file sam.yaml --stack-name downloader --capabilities CAPABILITY_IAM
  5. Once deployment has been successfully completed it should provide an API endpoint on the command console likehttps://[yourapi].execute-api.[region].amazonaws.com/Prod
  6. Make a note of the endpoint and also note the POST method endpoint will be like
    https://[yourapi].execute-api.[region].amazonaws.com/Prod/downloader

Developing application front end

For this walk through you will deploy a client application ASP.NET Blazor Web Assembly in an Amazon S3 bucket. So, for that create an Amazon S3 bucket name web-[your-unique- bucket-name].

  1. Open Visual Studio.
  2. From the Get Started page, choose Create a New Project and select Blazor App.
  3. Provide Solution name Downloader and Project name Client and choose Create.Create new project
  4. At this point select Blazor WebAssembly App and select Create. This will provide you the bootstrapping code that you need to build the front end.New Blazor app
  5. Navigate to Shared folder and replace codes in NavMenu.razor file with below code, this will give your web apps necessary navigation that you need
    <div class="top-row pl-4 navbar navbar-dark">
        <a class="navbar-brand" href="">Downloader-App</a>
        <button class="navbar-toggler" @onclick="ToggleNavMenu">
            <span class="navbar-toggler-icon"></span>
        </button>
    </div>
     
    <div class="@NavMenuCssClass" @onclick="ToggleNavMenu">
        <ul class="nav flex-column">
            <li class="nav-item px-3">
                <NavLink class="nav-link" href="download">
                    <span class="oi oi-cloud-download" aria-hidden="true"></span>Download
                </NavLink>
            </li>
     
        </ul>
    </div>
     
    @code {
        private bool collapseNavMenu = true;
        private string NavMenuCssClass => collapseNavMenu ? "collapse" : null;
        private void ToggleNavMenu()
        {
            collapseNavMenu = !collapseNavMenu;
        }
    }
    
  6. Create a folder name Models at the project level and create a class name VideoRequest.cs under Models. This class will be needed to hold form data.
    Create Model
  7. Add below properties in the VideoRequest class.
    using System;
    using System.Collections.Generic;
    using System.Text;
     
    namespace Client
    {
        public class VideoRequest
        {
            public string Url { get; set; }
            public string BucketName { get; set; }
            public string VideoTitle { get; set; }
        }
    }
    
  8. Under Pages create a new Razor component name Download.razor. This will hold the view needed by the application front end. Add razor component
  9. Add below code to render the user interface
    @page "/download"
    @using System.Net.Http
    @inject HttpClient Http
     
        <table class="table">
            <tr class="form-group">
                <td><span class="col-form-label">Youtube URL</span></td>
                <td><input type="text" class="input-group" @bind="videoRequest.Url" /></td>
            </tr>
            <tr class="form-group">
                <td><span class="col-form-label">Bucket Name</span></td>
                <td><input type="text" class="input-group" @bind="videoRequest.BucketName" /></td>
            </tr>
            <tr class="form-group">
                <td><span class="col-form-label">Video Title</span></td>
                <td><input type="text" class="input-group" @bind="videoRequest.VideoTitle" /></td>
            </tr>
            <tr class="form-group">
                <td></td>
                <td><button class="btn btn-primary" @onclick="DownloadVideo">Download </button></td>
            </tr>
            <tr class="form-group">
                <td></td>
                <td><h2 class="alert-info">@uploadMsg</h2></td>
            </tr>
        </table>
    
  10. Notice each input been bound to the model and it has a onclick event to post the data to back end.
  11. To handle the onclick event, ASP.NET Blazor lets you write C# code in the same file. So, append below code in the Download.razor file
    @code {
     
        private VideoRequest videoRequest = new VideoRequest();
        private string uploadMsg = string.Empty;
     
        private async Task DownloadVideo() {
     
            var response = await Http.PostAsJsonAsync("https://<yourapi>.execute-api.<region>.amazonaws.com/prod/downloader", videoRequest);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                uploadMsg = "File Successfully uploaded.";
            } 
        } 
    }
    

    Note: Replace the Amazon API Gateway endpoint received while deploying the application back end

  12. Choose Build, Build Solution.
  13. Press CTRL + Shift + B to make sure the current solution is building correctly.

Deploying application front end

Once you build your solution all static component you need to deploy will be put together by framework under wwwroot folder located under the project directory.

  1. Copy _framework folder from bin,Debug, netstandard2.1,wwwroot to the wwwroot folder Build output file
  2. Alternatively, you can also run command prompt (cmd) on this folder and run following command and copy the content available under web-publish, wwwroot.dotnet publish Client.csproj --output web-publishdotnet publish
  3. Open Window Command Prompt at this level (Downloader, Client, wwwroot) run aws s3 sync . s3://web-[your-unique-bucket-name] command to sync content from this folder to Amazon S3 bucket you have created before as shown in the screenshot below AWS S3 sync
  4. Launch an AWS CloudFormation stack from this deep link with existing_s3bucket_with_cloudfront.yamlfile available in GitHub repo to create a AWS CloudFront distribution in front of your Amazon S3 bucket.
  5. Please select below options while launching your stack and choose Next. Please make sure Amazon S3 bucket name should be same as your front end deployment bucket which is web-[your-unique-bucket-name]Launch AWS CloudFormation
  6. On this page keep everything default and choose Next again.
  7. Select Create Stack.
    Alternatively, you can also launch the CloudFormation stack from the Command Line Interface (CLI)  within the same folder where the existing_s3bucket_with_cloudfront.yaml file is located as

    aws cloudformation create-stack --stack-name pb-cloudfrontfors3  --template-body file://existing_s3bucket_with_cloudfront.yaml --parameters ParameterKey=OAIEnabled,ParameterValue=yes ParameterKey=S3BucketName,ParameterValue= web-[your-unique-bucket-name]

Launching  AWS Serverless video downloader

Once the AWS CloudFormation stack shows CREATE_COMPLETE click the AWS CloudFront domain name from the Outputs window of the AWS CloudFormation console. CloudFront endpoint

Now your video downloader app using Blazor WebAssembly is ready. Type a YouTube url with an existing Amazon S3 bucket that you have access to and video title and you will have your video downloaded for you. Final run output

Cleaning up

To avoid incurring future charges, on the AWS CloudFormation console, delete both the stacks created for this post. In order to do so

  • Open the AWS CloudFormation console .
  • On the Stacks page in the CloudFormation console, select the stack that you want to delete. The stack must be currently running.
  • In the stack details pane, choose Delete.
  • Select Delete stack when prompted.

About the Author

Pratip Bagchi Pratip Bagchi is a Partner Solutions Architect with Amazon Web Services.