How to Create And Consume Azure Function From ASP.NET Core

Consume Azure Function From ASP.NET Core Visual Studio 2019

In this Azure tutorial, we will discuss How to Create And Consume Azure Function From ASP.NET Core Along with this, we will also discuss a few other topics Develop An Azure Function using Visual Studio 2019 and we will also discuss Deploy Azure Function using Visual Studio 2019, and Create An ASP.NET Core application To consume the Azure Function.

How to Create And Consume Azure Function From ASP.NET Core? Perform the below steps to create and consume Azure Function from ASP.NET Core Application

  • Develop An Azure Function using Visual Studio 2019
  • Deploy Azure Function using Visual Studio 2019
  • Create An ASP.NET Core application To consume the Azure Function

How to Create And Consume Azure Function From ASP.NET Core

Before starting the actual development, we should know what are the Prerequisites needed to create and consume Azure Function from ASP.NET Core.

Prerequisites

  • The first thing we need is an Azure Account or Azure Subscription. Create an Azure Free Account now if you don’t have till now.
  •  Visual Studio 2019 with Azure development workload installed. Inst Visual Studio 2019 installed in your machine, install Visual Studio 2019 now.
  • We need Updated Azure Function tools

What we will do here?

We will create an Azure Function using Visual Studio 2019 and then we will test it using the Postman tool If it will work fine then We will Deploy the Azure Function using Visual Studio 2019 and Then we will create an Asp.Net Core application using Visual Studio 2019 and we will consume the Azure Function.

Create An Azure Function Using Visual Studio 2019

Open Visual Studio 2019 and Click on the Create New Project and then select Azure Functions as the template

On the Configure Your New Project window, Provide the name for your project and then provide a location to save the project and then click on the Create Button

consume azure function in c#

Select the HTTP trigger as the function trigger and select the Storage Emulator as the Storage Account (AzureWebJobsStorage) option and then choose Function as the Authorization level and then click on the Create button.

How to Create And Consume Azure Function From ASP.NET Core

Now you can able to see the Project got created successfully. Now add one more Entity class to the project name as RequestLeave.cs and add the below code in that file

Right-click on the Azure Function Solution —> Add —> Class

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

You can add the below lines of code to the RequestLeave.cs class file.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace LeaveDetils
{
    class RequestLeave
    {
        [JsonProperty(PropertyName = "employeeId")]
        public string EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public DateTime FromDate { get; set; }
        public DateTime ToDate { get; set; }
    }
}
Create And Consume Azure Function From ASP.NET Core

Now copy and paste the below code for your Azure Function class file below

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace LeaveDetils
{
    public static class Function1
    {
        [FunctionName("MyLeaveDetails")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("Logging the MyLeaveDetails request.");

            List<RequestLeave> lst = null;
            string EmployeeId = string.Empty;

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            EmployeeId = data?.employeeId;


            if (EmployeeId != null)
            {
                lst = new List<RequestLeave>();
                for (int i = 1; i < 4; i++)
                {
                    lst.Add(new RequestLeave() { EmployeeId = "40", EmployeeName = $"Employee {i}", FromDate = DateTime.Now.AddDays(-i - 1), ToDate = DateTime.Now.AddDays(-i) });
                }

                return (ActionResult)new OkObjectResult(lst);
            }

            return new BadRequestObjectResult("Pass an employee Id in the request body");
        }
    }
    }

You can see it below, You can replace the code above in your Azure Function class file

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

Below is the .csproj file code

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <AzureFunctionsVersion>v3</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.36" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

Now Let’s run the Application. Press the F5 button from your keyboard to run the Application. You can able to see it ran successfully and we got the expected output and got the Azure Function URL.

MyLeaveDetails: [GET,POST] http://localhost:7071/api/MyLeaveDetails

How to Develop And Consume Azure Function From ASP.NET Core

Test Azure Function Locally With Postman

Now we will test this Azure Function if it is working fine using the Postman App. Select the HTTP method as POST, Provide the JSON value for the Employee ID using the JSON format in the body, and then click on the Send button.

{

"employeeId": "40"

}

You can able to see, we got the expected output and the proper response code as 200 Ok. as shown below.

Consume Azure Function From ASP.NET Core

Since everything is working fine that we have verified just now, So now is the time to Publish the Azure Function to Azure.

Deploy Azure Function using Visual Studio 2019

Follow the below steps to deploy the Azure Function from Visual Studio 2019.

Right-click on the Azure Function Project —> click on the Publish link as shown below

How to Consume Azure Function From ASP.NET Core

On the Pick a publish target window, select the Create New option as shown below and then click on the Create Profile button

How to Consume Azure Functions From ASP.NET Core

On the App Service Create a new window, Provide a name for the App. Choose the correct subscription that you want to use here. Select an existing Resource group or if you don’t have the existing Resource Group then click on the New link to create a new Resource Group. Select the region and then finally select an existing Azure Storage account or if it is not there, then you can click on the New button to create a new Azure Storage account. Now click on the Create button to create the Azure Function App.

How to Create And Consume Azure Functions From ASP.NET Core

Once it will create the Azure Function App successfully, you can able to see the Publish window like below, Click on the Publish button to publish the Azure Function in Azure.

Develop And Consume Azure Functions From ASP.NET Core

Then Make sure to click on the Yes button from the below popup. Now Your Azure Function will get deployed to Azure Successfully.

Build And Consume Azure Functions From ASP.NET Core

Now we will navigate to the Azure Portal and will check if the Azure Function has deployed successfully or not.

Navigate to the Azure Portal and search for App Services and click on the search result App Services, You can able to see your Azure Function App. So click on your Azure Function App from the list that you have deployed just before.

On the Azure Function App, click on the Functions link from the left navigation, You can able to see the function on the right side as highlighted below. Click on the Azure function to navigate to the Azure Function.

Build And Consume Azure Function From ASP.NET Core

On the Azure Function page, click on the Code + Test from the left navigation. Now click on the Get Function URL button from the top and then click on the Copy button to copy to the clipboard as we are going to use in our code in the next steps.

How to Create And Consume Azure Functions From ASP.NET Core Visual Studio 2019

We have already copied the Azure Function URL and it should look like the below

https://leavedetilsemp.azurewebsites.net/api/MyLeaveDetails?code=GdC0hXI2swi6rb1Uobe/jpwuhSWv3yOA463eerr0uqrbdAwPPRjm8w==

Now just to make sure, it is working fine we will test the Azure Function using the Postman tool.

Now open the Postman app and use the above URL, Select the HTTP method as a POST then provide the employeeID value in JSON format and then click on the Send button. You can able to see below, we got the expected output with the Proper Response code as 200 Ok.

Create And Consume Azure Functions From ASP.NET Core Visual Studio 2019

Create An ASP.NET Core application To consume the Azure Function

Now Our Azure Function is completely ready to be called or consumed. So this is the time to Create An ASP.NET Core application To consume the Azure Function.

Open the Visual Studio 2019 and click on the Create New Project button.

Select the ASP.NET Core Web Application as the project template and then click on the Next button.

Create An ASP.NET Core application To consume the Azure Function

On the Configure your New Project window, Provide a name for the Project and then choose a location to save your project and then click on the Create button

Create An ASP.NET Core application Visual Studio 2019 To consume the Azure Function

Select the Web Application template on the Create a new ASP.NET Core web application window, click on the Create button now.

Create An ASP.NET Core application To consume the Azure Function  Visual Studio 2019

Now you can able to see the Project will get created successfully without any issues. Now you need to open the appsettings.Json file and you need to add the key-value pair for the Azure Function URL that you have copied from the Azure Portal.

Your appsettings.Json file should look like below

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "AppSettings": {
    "MyFunctionURL": "https://leavedetilsemp.azurewebsites.net/api/MyLeaveDetails?code=GdC0hXI2swi6rb1Uobe/jpwuhSWv3yOA463eerr0uqrbdAwPPRjm8w=="
  }

}
Create An ASP.NET Core application To call the Azure Function

Now you need to add a new class, Right-click on the Project —-> Add —-> Class and then provide the name as AppSettings.cs, and then click on the Create button and then Once the Class is created, Add the below line of code.

public class AppSettings
    {
        public string MyFunctionURL { get; set; }
    }

Now the next code change for the Startup.cs file as shown below, Add the last line in the ConfigureServices method like below.

 public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


           services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
        }

The function changes should look like below

How to Create An ASP.NET Core application To consume the Azure Function

Now again Right-click on the Project —> click on the Add —-> Class and provide the name for the class as RequestLeave.cs and then click on the Create button to create the new Entity class. Once the class will get created successfully, add the below lines of code

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyWebApplication
{
    public class RequestLeave
    {
        [JsonProperty(PropertyName = "employeeId")]
        public string EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public DateTime FromDate { get; set; }
        public DateTime ToDate { get; set; }
    }
}

Now, open the Index.cshtml.cs file and do the below changes. The first change is for the Constructor, You can add the below lines of code, and should look like below

  private AppSettings AppSettings { get; set; }

        public IndexModel(IOptions<AppSettings> settings)
        {
            AppSettings = settings.Value;
        }
asp.net core azure functions

The second change for the same file is we need to create the SerializeJsonIntoStream function and add the below lines of code

public static void SerializeJsonIntoStream(object value, Stream stream)
        {
            using (var stremw = new StreamWriter(stream, new UTF8Encoding(false), 1024, true))
            using (var jsonw = new JsonTextWriter(stremw) { Formatting = Formatting.None })
            {
                var js = new JsonSerializer();
                js.Serialize(jsonw, value);
                jsonw.Flush();
            }
        }

Once you add the SerializeJsonIntoStream function, then we need to do the third change on the same file and that is we will have to create the CreateHttpContent function and add the below lines of code as shown below

private static HttpContent CreateHttpContent(object content)
        {
            HttpContent httpContent = null;

            if (content != null)
            {
                var memorystresm = new MemoryStream();
                SerializeJsonIntoStream(content, memorystresm);
                memorystresm.Seek(0, SeekOrigin.Begin);
                httpContent = new StreamContent(memorystresm);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            }
            

            return httpContent;
        }

Now, we need to Add the OnPostAsync function code and that is the fourth change for the same file as shown below.

public async Task<IActionResult> OnPostAsync(string employeeID)
        {
            var Url = AppSettings.MyFunctionURL;
            

            dynamic content = new { employeeId = employeeID };

            CancellationToken cancellationToken;


            using (var myclient = new HttpClient())
            using (var myrequest = new HttpRequestMessage(HttpMethod.Post, Url))
            using (var httpContent = CreateHttpContent(content))
            {
                myrequest.Content = httpContent;

                using (var newresponse = await myclient
                    .SendAsync(myrequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
                    .ConfigureAwait(false))
                {

                    var MyListData = newresponse.Content.ReadAsAsync<List<RequestLeave>>();

                    ViewData["RequestLeave"] = MyListData.Result;

                    return Page();
                }
            }

        }

So these are the four code changes you need to do on the Index.cshtml.cs file. Now the complete file should look like below

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace MyWebApplication.Pages
{
    public class IndexModel : PageModel
    {
        private AppSettings AppSettings { get; set; }

        public IndexModel(IOptions<AppSettings> settings)
        {
            AppSettings = settings.Value;
        }
        public static void SerializeJsonIntoStream(object value, Stream stream)
        {
            using (var stremw = new StreamWriter(stream, new UTF8Encoding(false), 1024, true))
            using (var jsonw = new JsonTextWriter(stremw) { Formatting = Formatting.None })
            {
                var js = new JsonSerializer();
                js.Serialize(jsonw, value);
                jsonw.Flush();
            }
        }
        private static HttpContent CreateHttpContent(object content)
        {
            HttpContent httpContent = null;

            if (content != null)
            {
                var memorystresm = new MemoryStream();
                SerializeJsonIntoStream(content, memorystresm);
                memorystresm.Seek(0, SeekOrigin.Begin);
                httpContent = new StreamContent(memorystresm);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            }
            

            return httpContent;
        }
        public async Task<IActionResult> OnPostAsync(string employeeID)
        {
            var Url = AppSettings.MyFunctionURL;
            

            dynamic content = new { employeeId = employeeID };

            CancellationToken cancellationToken;


            using (var myclient = new HttpClient())
            using (var myrequest = new HttpRequestMessage(HttpMethod.Post, Url))
            using (var httpContent = CreateHttpContent(content))
            {
                myrequest.Content = httpContent;

                using (var newresponse = await myclient
                    .SendAsync(myrequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
                    .ConfigureAwait(false))
                {

                    var MyListData = newresponse.Content.ReadAsAsync<List<RequestLeave>>();

                    ViewData["RequestLeave"] = MyListData.Result;

                    return Page();
                }
            }

        }
    }
}

Now we will have to do the final changes i.e. Index.cshtml file changes, You will have to add the below lines of code in that file. Better to Replace the complete code in that file

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="row">
    <div class="col-md-12">
        <hr />
        @{
            List<RequestLeave> mylst = ViewData["RequestLeave"] as List<RequestLeave>;

            if (mylst != null)
            {
                foreach (var myitem in mylst)
                {
                    <p>@myitem.EmployeeName - @myitem.EmployeeId - @myitem.FromDate.ToShortDateString() - @myitem.ToDate.ToShortDateString()</p>
                }
            }
        }
        <hr />
        <form method="post">

            <label for="EmpName">TsInfo Employee Id</label>
            <input type="text" id="employeeID" name="employeeID" placeholder="TSInfo Employee Id" />
            <input type="submit" />
        </form>
    </div>
</div>

Now we will run the Application and will check if the functionality is working fine as expected. Press F5 to run the application and you can put any EmployeeID and click on the Submit button, You can able to see, we got the expected output as shown below without any issues.

Build An ASP.NET Core application To consume the Azure Function

This is How to Create And Consume Azure Function From ASP.NET Core by following the above-mentioned steps.

You may also like following the below articles

Wrapping Up

Well, in this article, we discussed How to Create And Consume Azure Function From ASP.NET Core, Develop An Azure Function using Visual Studio 2019 and we also discussed Deploy Azure Functions using Visual Studio 2019, and Create An ASP.NET Core application To consume the Azure Function. Hope you have enjoyed this article !!!