How to call Azure Function from C#

Consume Azure Function From ASP.NET Core Visual Studio 2019

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

Azure web functions

Test Azure Function Locally With Postman

We will test this Azure Function to see if it works 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 the Send button.

{

"employeeId": "40"

}

As shown below, we got the expected output and the proper response code as 200 OK.

azure function c#

Since everything is working fine, which we have verified just now, 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

sample azure function c#

Create a new window on the App Service and 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, 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.

create azure function c#

Once it successfully creates the Azure Function App, you can see the Publish window 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 be deployed to Azure successfully.

how to pass multiple parameters in azure function c#

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

Navigate to the Azure Portal, 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 you have deployed just before.

On the Azure Function App, click on the Functions link from the left navigation. You can 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 will use in our code in the next steps.

c# azure function example

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

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

We will test the Azure Function using the Postman tool to ensure it is working fine.

Now open the Postman app and use the above URL. Select the HTTP method as a POST, provide the employeeID value in JSON format, and click the Send button. We got the expected output with the Proper Response code as 200 OK below.

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.

  1. Open the Visual Studio 2019 and click on the Create New Project button.
  2. Select the ASP.NET Core Web Application as the project template and click Next.
how to pass multiple parameters in azure function c#

3. On the Configure your New Project window, Provide a name for the Project, 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

4. 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 see the Project will be created successfully without any issues. You must open the appsettings.Json file and add the key-value pair for the Azure Function URL you copied from the Azure Portal.

Your appsettings.Json file should look like the below

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

}
c# azure function example

Now, you need to add a new class. Right-click on the Project —-> Add —-> Class 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, then click on the Create button to create the new Entity class. Once the class is 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 make the below changes. The first change is for the Constructor. You can add the below lines of code, and it 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;
        }

We need to Add the OnPostAsync function code, 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 must 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 make the final changes, i.e., the 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 check if the functionality works as expected. Press F5 to run the application, and you can enter any EmployeeID and click on the Submit button. We got the expected output, as shown below, without any issues.

azure functions c#

You may also like following the articles below

Wrapping Up

In this article, we discussed How to call Azure Function from C#. I hope you have enjoyed this article !!!