Introduction
In my last article, we have seen how to develop Azure Functions using the Azure portal. That is good for experimenting but in a real scenario, we need to develop the functions in the local environment. Once it’s ready for production, we need to deploy it. In this article, I’m going to explain how to develop and deploy the Azure Functions using Visual Studio tooling.
Prerequisites
- Visual Studio 2017 with Azure Development workload
- Azure Subscription
- Latest Azure Function tools
- Basic knowledge of Azure Storage Service
What we will learn
- Creating an Azure Functions app in Visual Studio
- Deploying the Azure Functions using Visual Studio
Creating an Azure Functions app in Visual Studio
Step 1
Open Visual Studio, select New->Project from the file menu.
Step 2
In the “New Project” window, from the “Installed” section, click on Cloud >> Azure Functions template and name it. In my case, I named it as MyAzureFunction, as shown in the below figure.
Step 3
In the next window, we need to choose the trigger for our Azure Function. In my case, I have selected HTTP Trigger. For Storage Account, let it be Storage Emulator. Later, while deploying or doing bindings, we need to provide the Azure Storage Account connection string.
We can provide the access right to Function level or else, we can make it anonyms. By default, the access right will be at the Function level.
Once it is done, click OK to create a project.
Step 4
The project contains the class file and the local setting file named local.setting.json will contain a Key and value pair of Azure Storage connection string.
[FunctionName("MyFunctionDemo")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
// parse query parameter
string name = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
.Value;
if (name == null)
{
// Get request body
dynamic data = await req.Content.ReadAsAsync<object>();
name = data?.name;
}
return name == null
? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
: req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
}
}
The above function will accept both get and post requests. If the request is GET type, it will get the value from the query string with the key as name and for POST, it will get a value of key name from the request body. Finally, it will respond with a string “Hello “ to the user.
Let’s run the app and test it in Postman.