A Step-by-Step Guide to Creating and Deploying an Azure Function using ASP.NET Core

Waqas Ahmed
5 min readMay 8, 2023

--

Creating and Deploying an Azure Function using ASP.NET Core
Creating and Deploying an Azure Function using ASP.NET Core

Azure Serverless Functions are a type of cloud computing service offered by Microsoft Azure. They allow you to run small, single-purpose code functions in the cloud without the need for a dedicated server or virtual machine.

With Azure Serverless Functions, you can write your code in your preferred programming language, such as C#, Java, JavaScript, or Python. The code is executed only when triggered by an event, such as an HTTP request, a message in a queue, or a change in a database.

Azure Serverless Functions are scalable and cost-effective, as you only pay for the exact amount of resources your functions consume while they are running. This makes them an ideal choice for applications with unpredictable or sporadic traffic patterns.

You can use Azure Serverless Functions for a variety of tasks, such as processing data, running background tasks, and integrating with other Azure services. They also provide built-in security features, such as identity and access management, to help protect your applications and data.

Here are the step-by-step instructions for setting up an Azure Function in the Azure Portal:

  1. Log in to the Azure Portal at https://portal.azure.com/
  2. Click on the “Create a resource” button (+) on the left side of the page.
  3. In the “Search the Marketplace” field, type “Function App” and select “Function App” from the dropdown menu.
  4. Click the “Create” button to begin creating a new Function App.
  5. Fill in the required fields on the “Basics” tab, including the subscription, resource group, and name of the Function App.
  6. Choose the runtime stack and version for your Function App. You can select from several options, such as .NET, Node.js, and Python.
  7. Under the “Hosting” section, select “Consumption Plan” as the hosting plan. This will allow your function to scale automatically and only charge you for the resources used while the function is running.
  8. Select the “Storage Account” that you want to use or create a new one.
  9. Click “Review + create” to review your settings and create the Function App.
  10. Click “Create” to create the Function App.

Once your Function App is created, you can add functions to it by clicking on the “Functions” section in the left-hand menu and selecting “New Function.” From there, you can choose from several templates, including HTTP trigger, Timer trigger, and Cosmos DB trigger, to create your function.

Here’s an example of how to create an Azure Serverless Function using ASP.NET Core and Swagger:

First, you will need to create a new Azure Function project in Visual Studio:

  1. Open Visual Studio and select “Create a new project”.
  2. Select “Azure Functions” from the list of project templates and click “Next”.
  3. Choose “Azure Functions v3 (.NET Core)” and click “Next”.
  4. Enter a name for your project and click “Create”.

Once your project is created, you can add Swagger support to it using the following steps:

  1. Install the Swashbuckle.AspNetCore NuGet package by running the following command in the Package Manager Console: Install-Package Swashbuckle.AspNetCore
  2. Open the Startup.cs file in your project and add the following code to the ConfigureServices method:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My Azure Function", Version = "v1" });
});

3. Add the following code to the Configure method:

app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My Azure Function v1");
});

4. Create a new Azure Function by right-clicking on the Functions folder in your project and selecting “Add” > “New Azure Function”.

5. Choose “HTTP trigger” as the function type and enter a name for your function.

6. In the “Authentication” section, choose “Anonymous” as the authentication level.

7. Replace the contents of the function’s .cs file with the following code:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

namespace MyFunctionNamespace
{
public static class MyFunction
{
[FunctionName("MyFunction")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");

string name = req.Query["name"];

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

return new OkObjectResult($"Hello, {name}");
}
}
}

This code defines an HTTP trigger function that takes an optional “name” parameter and returns a greeting message.

Now you can run your function and test it using Swagger by following these steps:

  1. Start the project in Visual Studio by pressing F5.
  2. Open a web browser and navigate to http://localhost:7071/swagger/index.html.
  3. Click on your function in the list of available APIs.
  4. Click the “Try it out” button.
  5. Enter a name in the “name” field (optional) and click “Execute”.
  6. The response should display a greeting message with the name you entered (or a default message if no name was entered).

Here are the steps to deploy your Azure Function created using ASP.NET Core in the Azure Portal:

  1. In the Azure Portal, go to the Function App that contains the function you want to deploy.
  2. Click on the “Functions” section in the left-hand menu and click on the function you want to deploy.
  3. Click on the “Code + Test” tab in the top menu to open the function’s code editor.
  4. In the code editor, click on the “Deploy” button in the top menu.
  5. Select the deployment option that you want to use. You can choose between “Local Git,” “FTP,” or “GitHub.”
  6. If you choose “Local Git,” follow the prompts to create a new deployment user and to download a deployment profile. You’ll use this profile to push your code to the Function App.
  7. If you choose “FTP,” you’ll need to use an FTP client to upload your code files to the Function App.
  8. If you choose “GitHub,” you’ll need to authenticate with GitHub and select the repository that contains your code.
  9. Once your code is deployed, you can test your function by clicking on the “Test/Run” button in the top menu.

That’s it! You’ve successfully deployed your Azure Function created using ASP.NET Core to the Azure Portal using either the “Local Git,” “FTP,” or “GitHub” deployment option.

Here’s how you can deploy your Azure Function created using ASP.NET Core as a Docker container:

  1. Create a Dockerfile for your Azure Function. Here’s an example:
# Use the .NET Core runtime as a base image
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-alpine

# Set the working directory to /app
WORKDIR /app

# Copy the source code into the container
COPY . /app

# Expose the port that the function will listen on
EXPOSE 80

# Set the environment variable for the Azure Functions runtime
ENV AzureWebJobsScriptRoot=/app

# Start the Azure Functions runtime
ENTRYPOINT ["dotnet", "MyFunction.dll"]

2. Build the Docker image:

docker build -t myfunction .

Replace myfunction with the name you want to give your Docker image.

3. Run the Docker container:

docker run -d -p 80:80 myfunction

This will start a new Docker container with your Azure Function running inside.

4. Verify that your function is working correctly by sending an HTTP request to http://localhost:80/api/MyFunction?name=John.

Replace MyFunction with the name of your function and name=John with any query parameters your function expects.

That’s it! You’ve successfully deployed your Azure Function created using ASP.NET Core as a Docker container.

--

--

Waqas Ahmed
Waqas Ahmed

Written by Waqas Ahmed

Microsoft Azure Enthusiast ☁ | Principal Software Engineer | Angular | React.Js | .Net Core | .Net | Azure | Micro Services 👉 https://bit.ly/3AhEyOz

No responses yet