How To Create Azure Function In Visual Studio

How To Create Azure Functions In Visual Studio

This Azure tutorial will discuss how to create Azure Functions in Visual Studio.

Create Azure Function In Visual Studio 2019

You can develop the Azure Functions using Visual Studio, just like you develop a .NET Project. When you choose Visual Studio as IDE to develop the Azure Function, you will get many benefits, like you can build, debug, and test the functionality in your local machine properly before moving to the Cloud.

Once you develop and test your Azure function successfully on your local machine, you can publish your Azure Function directly from your local environment to Azure with the help of Visual Studio in a fraction of a second.

You can write the code for your function in C# and use the C# attribute to declare your Azure Function and utilize all the benefits of Visual Studio.

This article will show how to develop and deploy Azure Functions using Visual Studio. We will be creating a new Azure Function project. We will see how we can build and run the Project in our local environment, and then we will see how we can publish that to Azure from our Visual Studio.

Before starting the actual development activities, we need a few things as Prerequisites

Prerequisites

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

Let’s discuss the steps to create Azure Functions In Visual Studio.

Create Azure Function In Visual Studio 2019 Step By Step

So, we will use the latest version of Visual Studio, i.e., Visual Studio 2019, for our development activities. As part of the development activity, we will create the Azure Function first, and then deploy the Azure Functions using Visual Studio.

Below are the steps that need to be followed

1. Open Visual Studio 2019.

How To Create Azure Functions In Visual Studio

2. Once the Visual Studio loaded successfully, click the Create a new project button from the Get Started window.

How To Create Azure Functions In Visual Studio 2019

3. On the Create a new project window, Search for the Azure Functions template, choose the Azure Functions, and click the Next button.

azure functions tutorial

4. On the Configure Your New Project window, Enter the Project name, choose a location where you want to create the project, and click the Create button.

how to create azure function in visual studio

5. On the Create a new Azure Functions Application window, we need to choose the trigger for our Azure Function, so choose the Http trigger as the trigger option. For the Storage Account (AzureWebJobsStorage) option, select Storage Emulator and Choose the Authorization level option as Function. So basically keep all the default options as it is as of now.

azure function tutorial

6. As you can see below, the Project was created successfully without any issues.

create azure function in visual studio

7. Open the local.settings.json file and check it contains the below code with a key-value pair of Azure Storage connection string.

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet"
    }
}
how to create function app in azure

8. If you open the Function1.cs file, you can see a predefined method like the one below

This function will help to perform both the get and post-operation. if you are performing a GET request, then it will get the value from the query string in the URL with the key as name, and if you are performing a POST operation, it will get the name key value from the request body, and then it will return with the string “Hello {name value}” to us.

[FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "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 = name ?? data?.name;

            return name != null
                ? (ActionResult)new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }
how to create a azure function in visual studio

How To Run Azure Function Locally In Visual Studio 2019

Now Press F5 to run the project, and once it runs successfully, We can check with the Postman tool if it is working fine

create azure function in visual studio

Now open the Postman app and try running the above endpoint: http://localhost:7071/api/Function1. You can able to see that we got the desired output.

how to create a azure function in visual studio

So, We performed the GET operation, Now the time came to see the post-operation. Let’s modify the function a bit and remove the GET from there only we will keep POST only there like below.

 [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            // string jsonContent = await req.Content.ReadAsStringAsync();
            //string jsonContent = await req.Content.ReadAsStringAsync();
            //var myDetails = JsonConvert.DeserializeObject<UserDetails>(jsonContent);
            //log.LogInformation($"Order {myDetails.UserId} received from {myDetails.UserEmail} for product{myDetails.UserId}");
            //await outputQueue.AddAsync(myDetails);


            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 = name ?? data?.name;

            return name != null
                ? (ActionResult)new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }

The function should look exactly below

azure function in visual studio

Now, Run the application by pressing F5, or you can click on the Start Debugging option. You can see the below screen. Copy the function URL http://localhost:7071/api/Function1.

Create Azure Functions In Visual Studio 2017

Open the Postman app, paste the URL, select the Post option, and click the Send button. Now it will show you, “Please pass a name on the query string or in the request body.”

create azure function in visual studio 2015

Now we need to provide a query string parameter along with the URL and then again click on the Send button. As you can see below, we got the expected output, and the Status code is 200 OK.

Create a function in Azure using Visual Studio

If you can check out the flow, you can debug Azure Function locally.

Now is the time to deploy Azure Function from Visual Studio.

Also, you can create the Azure Functions using C# in Visual Studio Code.

You may also like following the articles below

Conclusion

This article discussed how to create Azure Functions in Visual Studio 2019. I hope you have enjoyed this article !!!