Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

How to call an Azure function from an ASP.NET Core MVC application

Save for later
  • 10 min read
  • 03 May 2018

article-image

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

[box type="shadow" align="" class="" width=""]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.[/box]

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:

azure-function-asp-net-core-mvc-application-img-0

  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:

azure-function-asp-net-core-mvc-application-img-1

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

azure-function-asp-net-core-mvc-application-img-2

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):

azure-function-asp-net-core-mvc-application-img-3

  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:

azure-function-asp-net-core-mvc-application-img-44. 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:

azure-function-asp-net-core-mvc-application-img-5

  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 <body></body> tags.

  1. Your Index.cshtml file should now look as follows:

@{ 
    ViewData["Title"] = "Login Page";     
} 
 
<div class="limiter"> 
    <div class="container-login100"> 
        <div class="wrap-login100"> 
            <div class="login100-pic js-tilt" data-tilt> 
                <img src="images/img-01.png" alt="IMG"> 
            </div> 
 
            <form class="login100-form validate-form"> 
                <span class="login100-form-title"> 
                    Member Login 
                </span> 
 
                <div class="wrap-input100 validate-input" 
                 data-validate="Valid email is required: 
                  ex@abc.xyz"> 
                    <input class="input100" type="text" 
                     name="email" placeholder="Email"> 
                    <span class="focus-input100"></span> 
                    <span class="symbol-input100"> 
                        <i class="fa fa-envelope"
                         aria-hidden="true"></i> 
                    </span> 
                </div> 
 
                <div class="wrap-input100 validate-input" 
                 data-validate="Password is required"> 
                    <input class="input100" type="password" 
                     name="pass" 
                     placeholder="Password"> 
                    <span class="focus-input100"></span> 
                    <span class="symbol-input100"> 
                        <i class="fa fa-lock"
                         aria-hidden="true"></i> 
                    </span> 
                </div> 
 
                <div class="container-login100-form-btn"> 
                    <button class="login100-form-btn"> 
                        Login 
                    </button> 
                </div> 
 
                <div class="text-center p-t-12"> 
                    <span class="txt1"> 
                        Forgot 
                    </span> 
                    <a class="txt2" href="#"> 
                        Username / Password? 
                    </a> 
                </div> 
 
                <div class="text-center p-t-136"> 
                    <a class="txt2" href="#"> 
                        Create your Account 
                        <i class="fa fa-long-arrow-right m-l-5" 
                         aria-hidden="true"></i> 
                    </a> 
                </div> 
            </form> 
        </div> 
    </div> 
</div>

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:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - CoreMailValidation</title>
<link rel="icon" type="image/png" href="~/images/icons/favicon.ico" />
<link rel="stylesheet" type="text/css" href="~/vendor/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="~/fonts/font-awesome-4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="~/vendor/animate/animate.css">
<link rel="stylesheet" type="text/css" href="~/vendor/css-hamburgers/hamburgers.min.css">
<link rel="stylesheet" type="text/css" href="~/vendor/select2/select2.min.css">
<link rel="stylesheet" type="text/css" href="~/css/util.css">
<link rel="stylesheet" type="text/css" href="~/css/main.css">
</head>

<body>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© 2018 - CoreMailValidation</p>
</footer>
</div>
<script src="~/vendor/jquery/jquery-3.2.1.min.js"></script>
<script src="~/vendor/bootstrap/js/popper.js"></script>
<script src="~/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="~/vendor/select2/select2.min.js"></script>
<script src="~/vendor/tilt/tilt.jquery.min.js"></script>
<script>
$('.js-tilt').tilt({
scale: 1.1
})
</script>
<script src="~/js/main.js"></script>
@RenderSection("Scripts", required: false)
</body>

</html>

  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:
  2. Unlock access to the largest independent learning library in Tech for FREE!
    Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
    Renews at €18.99/month. Cancel anytime

azure-function-asp-net-core-mvc-application-img-6


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:

azure-function-asp-net-core-mvc-application-img-7


 

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:

azure-function-asp-net-core-mvc-application-img-8 2. Your project should now look as follows. You will see the model added to the Models folder:

azure-function-asp-net-core-mvc-application-img-9

  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<string> 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.

What is ASP.NET Core?

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

How to dockerize an ASP.NET Core application