9 min read

In this tutorial, we’ll learn how to call an Azure Function from an ASP.NET Core MVC application.

This article is an extract from the book C# 7 and .NET Core Blueprints, authored by Dirk Strauss and Jas Rademeyer. This book is a step-by-step guide that will teach you essential .NET Core and C# concepts with the help of real-world projects.

We will get started with creating an ASP.NET Core MVC application that will call our Azure Function to validate an email address entered into a login screen of the application:

This application does no authentication at all. All it is doing is validating the email address entered. ASP.NET Core MVC authentication is a totally different topic and not the focus of this post.
  1. In Visual Studio 2017, create a new project and select ASP.NET Core Web Application from the project templates. Click on the OK button to create the project. This is shown in the following screenshot:
ASP.Net Core Web application
  1. On the next screen, ensure that .NET Core and ASP.NET Core 2.0 is selected from the drop-down options on the form. Select Web Application (Model-View-Controller) as the type of application to create.

Don’t bother with any kind of authentication or enabling Docker support. Just click on the OK button to create your project:

Authentication
  1. After your project is created, you will see the familiar project structure in the Solution Explorer of Visual Studio:
Solution explorer

Creating the login form

For this next part, we can create a plain and simple vanilla login form. For a little bit of fun, let’s spice things up a bit. Have a look on the internet for some free login form templates:


  1. I decided to use a site called colorlib that provided 50 free HTML5 and CSS3 login forms in one of their recent blog posts. The URL to the article is: https://colorlib.com/wp/html5-and-css3-login-forms/.
  2. I decided to use Login Form 1 by Colorlib from their site. Download the template to your computer and extract the ZIP file. Inside the extracted ZIP file, you will see that we have several folders. Copy all the folders in this extracted ZIP file (leave the index.html file as we will use this in a minute):
Login form 1 by Colorlib
  1. Next, go to the solution for your Visual Studio application. In the wwwroot folder, move or delete the contents and paste the folders from the extracted ZIP file into the wwwroot folder of your ASP.NET Core MVC application. Your wwwroot folder should now look as follows:
ASP.NET Core MVC application4. Back in Visual Studio, you will see the folders when you expand the wwwroot node in the CoreMailValidation project.
5. I also want to focus your attention to the Index.cshtml and _Layout.cshtml files. We will be modifying these files next:
Solution explorer
  1. Open the Index.cshtml file and remove all the markup (except the section in the curly brackets) from this file. Paste the HTML markup from the index.html file from the ZIP file we extracted earlier.
Do not copy the all the markup from the index.html file. Only copy the markup inside the tags.
  1. Your Index.cshtml file should now look as follows:
@{ 
    ViewData["Title"] = "Login Page";     
} 
 
The code for this chapter is available on GitHub here:
  1. Next, open the Layout.cshtml file and add all the links to the folders and files we copied into the wwwroot folder earlier. Use the index.html file for reference. You will notice that the _Layout.cshtml file contains the following piece of code—@RenderBody(). This is a placeholder that specifies where the Index.cshtml file content should be injected. If you are coming from ASP.NET Web Forms, think of the _Layout.cshtml page as a master page. Your Layout.cshtml markup should look as follows:



@ViewData["Title"] - CoreMailValidation

@RenderBody()

© 2018 - CoreMailValidation

@RenderSection("Scripts", required: false)
  1. If everything worked out right, you will see the following page when you run your ASP.NET Core MVC application. The login form is obviously totally non-functional:
member login

However, the login form is totally responsive. If you had to reduce the size of your browser window, you will see the form scale as your browser size reduces. This is what you want. If you want to explore the responsive design offered by Bootstrap, head on over to https://getbootstrap.com/ and go through the examples in the documentation:

mobile member login screen

 

The next thing we want to do is hook this login form up to our controller and call the Azure Function we created to validate the email address we entered.

Let’s look at doing that next.

Hooking it all up

To simplify things, we will be creating a model to pass to our controller:

  1. Create a new class in the Models folder of your application called LoginModel and click on the Add button:
Core mail validation 2. Your project should now look as follows. You will see the model added to the Models folder:
core mail validation
  1. The next thing we want to do is add some code to our model to represent the fields on our login form. Add two properties called Email and Password:
      namespace CoreMailValidation.Models 
      { 
        public class LoginModel 
        { 
          public string Email { get; set; } 
          public string Password { get; set; } 
        } 
      }
  1. Back in the Index.cshtml view, add the model declaration to the top of the page. This makes the model available for use in our view. Take care to specify the correct namespace where the model exists:
      @model CoreMailValidation.Models.LoginModel 
      @{ 
        ViewData["Title"] = "Login Page"; 
      }
  1. The next portion of code needs to be written in the HomeController.cs file. Currently, it should only have an action called Index():
      public IActionResult Index() 
      { 
        return View(); 
      }
  1. Add a new async function called ValidateEmail that will use the base URL and parameter string of the Azure Function URL we copied earlier and call it using an HTTP request. I will not go into much detail here, as I believe the code to be pretty straightforward. All we are doing is calling the Azure Function using the URL we copied earlier and reading the return data:
      private async Task ValidateEmail(string emailToValidate) 
      { 
        string azureBaseUrl = "https://core-mail-
         validation.azurewebsites.net/api/HttpTriggerCSharp1"; 
        string urlQueryStringParams = $"?
         code=/IS4OJ3T46quiRzUJTxaGFenTeIVXyyOdtBFGasW9dUZ0snmoQfWoQ
          ==&email={emailToValidate}"; 
 
        using (HttpClient client = new HttpClient()) 
        { 
          using (HttpResponseMessage res = await client.GetAsync(
           $"{azureBaseUrl}{urlQueryStringParams}")) 
          { 
            using (HttpContent content = res.Content) 
            { 
              string data = await content.ReadAsStringAsync(); 
              if (data != null) 
              { 
                return data; 
              } 
              else 
                return ""; 
            } 
          } 
        } 
      }
  1. Create another public async action called ValidateLogin. Inside the action, check to see if the ModelState is valid before continuing.
For a nice explanation of what ModelState is, have a look at the following article—https://www.exceptionnotfound.net/asp-net-mvc-demystified-modelstate/.
  1. We then do an await on the ValidateEmail function, and if the return data contains the word false, we know that the email validation failed. A failure message is then passed to the TempData property on the controller.
The TempData property is a place to store data until it is read. It is exposed on the controller by ASP.NET Core MVC. The TempData property uses a cookie-based provider by default in ASP.NET Core 2.0 to store the data. To examine data inside the TempData property without deleting it, you can use the Keep and Peek methods. To read more on TempData, see the Microsoft documentation here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?tabs=aspnetcore2x.

If the email validation passed, then we know that the email address is valid and we can do something else. Here, we are simply just saying that the user is logged in. In reality, we will perform some sort of authentication here and then route to the correct controller.

So now you know how to call an Azure Function from an ASP.NET Core application. If you found this tutorial helpful and you’d like to learn more, go ahead and pick up the book C# 7 and .NET Core Blueprints.

Read Next

What is ASP.NET Core?

Why ASP.NET makes building apps for mobile and web easy

How to dockerize an ASP.NET Core application

 

 


Subscribe to the weekly Packt Hub newsletter. We'll send you the results of our AI Now Survey, featuring data and insights from across the tech landscape.

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here