How to call Azure Function from C#

This Azure tutorial will discuss the steps to call Azure Function from c#.

How to call Azure Function from C#? Perform the below steps to create and call Azure Function from C#

  • 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 call Azure Function from C#

Before starting the development, we should know the Prerequisites for calling Azure Function from c#.

Prerequisites

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

What will we do here?

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

Create An Azure Function Using Visual Studio 2019

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

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

c# call azure function

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

how to call azure function from c#

3. Now you can see the Project was 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 azure function from c#

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; }
    }
}
how to call azure function

Now copy and paste the code below 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 azure function from web api c#

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. It ran successfully, and we got the expected output and the Azure Function URL.

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