Running Vue.js on ASP.NET Core Applications

Vue.js has recently got many attentions as it is relatively easier to learn and lighter in size, comparing to other popular frameworks like Angular 1, Angular 2 or React. By providing a middleware, ASP.NET Core supports those front-end frameworks such as Angular2, Aurelia, React, Knockout, etc, while Vue has been excluded out-of-the-box. Even though we can find many good articles and code samples to integrate Vue and ASP.NET Core, as they don’t use the basic template that Vue is providing, it’s a little difficult for developers to apply at their first glance, who want to use both Vue and ASP.NET Core with minimum integration efforts. In this post, we are going to integrate Vue.js and ASP.NET Core using their basic templates, with minimum modification.

The code sample used in this post can be found at here.


In order to support front-end development in ASP.NET Core, Visual Studio uses Bower. However, as we are already aware how fast front-end development environment changes, another option like Webpack helps developers work a lot easier by offering bundling, moduling and so forth. ASP.NET Core, of course supports Webpack as a separate extension. Microsoft.AspNetCore.SpaServices helps developers integrate front-end frameworks using Webpack with ease.


Throughout this post, we need some preparations:

We can also use Visual Studio Code (VSC), but we’re assuming to use VS for this post.

Creating ASP.NET Core Web Application

Open Visual Studio and create a new ASP.NET Core web application project. As this web application likely uses .NET Core version 1.0.1, we need to update it to 1.1 by updating global.json:

Also, update project.json so that all NuGet packages in the web application can be complied to .NET Core 1.1:

As mentioned earlier, we’re using Webpack instead of Bower, so remove Bower-related configuration files as well as ASP.NET Core native bundling & minification setting files:

  • .bowerrc
  • bower.json
  • bundleconfig.json

And finally, all directories and files under the wwwroot directory need to be deleted. We’re all set now at the ASP.NET Core application side. Let’s add Vue.

Installing Vue.js

We can use Vue as a stand-alone library by simply including the script from CDN. However, if we want to use its powerful features especially for componentising, module bundlers like Webpack should be considered. In order to use Webpack for Vue.js, if node.js and npm have already been installed, install vue-cli:

Then, install the basic template by running the following command:

During installation, just leave all the question as default value and finally template gets installed. Now, run the following command to install all npm packages and run the Vue app:

Since Vue uses the port number of 8080, we can see the result as expected. However, this is just a Vue app running independently, not the one integrated with ASP.NET Core. Let’s move on.

Integrating Vue.js with ASP.NET Core

This is the main part of this post. We need to touch configurations at both sides.

Configuring Vue.js

First things first. We need to install the npm package, aspnet-webpack, to enable communication between front-end framework and back-end application through Webpack:

Once installed, update config/index.js to setup the root directory:

And finally, create webpack.config.js and save it to the root directory of the ASP.NET Core project:

We now got Vue.js setup done. What’s next?

Configuring ASP.NET Core

aspnet-webpack corresponding package in the ASP.NET Core side is Microsoft.AspNetCore.SpaServices. Install it through NuGet package manager and register a middleware at Startup.cs:

We also need to add a routing configuration for SPA like above. Is the ASP.NET Core side relatively simple? Let’s punch the F5 key to run the app and see how it’s going.

We now can see a different port number that is handled by the ASP.NET Core app. So, technically we completed integration between Vue.js and ASP.NET Core! How can we ensure if they are actually working together? Let’s implement a basic AJAX call to see whether they get along with each other. Of course further modification is required. Who can stop us?

Handling AJAX Request/Response

As Vue.js core is lightweight, if we want to implement more sophisticated works like handling AJAX request/response, we need to install another npm extension called vue-resource.

Once installed, add it to the Vue instance for use. Update src/main.js like:

Now we need to implement AJAX request/response codes. Open /src/components/Hello.vue and modify it like:

What we can expect from this change is the message Welcome to Your Vue.js App will be replaced with the value from res.body.message. Now we need to implement the Web API. Here’s the Web API controller and action:

All good. Build the app, press the F5 key and confirm the result.

We can see Hello World, instead of the original message.

Side note: Another benefit of using Webpack is Hot Module Replacement (HMR). As long as the app is up and running on our local machine, we can instantly change something and check the result with no time, without reloading the page. Of course, if we install .NET Core Watcher tool, we don’t even need to rebuild and rerun the app itself either.

Deploying App to Azure

We’ve built an ASP.NET Core web application with Vue.js. Now it’s time for deployment. We don’t use View features provided by ASP.NET Core. Instead we just use a static(?) wwwroot/index.html. In our local development, we don’t really have to worry about that as our development environment automatically detects that. However, in a production environment, we have to specify we’re using the static index.html page; otherwise Azure web app can’t recognise it. To enable this feature, we need to update Startup.cs:

Make sure that the UseDefaultFiles() method must always come before the UseStaticFiles() method. Finally update deployment/publish related settings in project.json for Vue.js:

Everything is done! Deploy this web app to Azure and see the result. Can we see it as expected?

So far, we have installed Vue.js, integrated it with ASP.NET Core, implemented whether both are working together or not, and deployed the app to Azure web app instance. Some may think this looks too complicated, but actually, it’s not that tricky. Rather, we’ve got another option on ASP.NET Core application development using a different front-end framework. As long as a new front-end framework emerges and it supports Webpack, we can make it working like this approach. Now, for the next step, let’s build a real business solution!

Integrating Microsoft Flow with Azure Functions for Non-IT People

Microsoft Flow (Flow) creates automated workflows between various apps and services so that users can get notifications, collect data and more. This is similar to Azure Logic Apps (Logic Apps), but has different target audiences such as marketing, sales or all other non-IT related people. This document provides high-level comparisons between Flow, Logic Apps and Azure Functions.

Flow contains comprehensive number of pre-defined workflows called templates so we can just simply choose one of them, provide necessary information and use it. If there is no template suitable for our purpose, we can create a new template from scratch using pre-defined triggers and actions. If there is no trigger or action pre-defined, we can use a simple HTTP trigger using Azure Functions. In this post, we are going to have a look how use Azure Functions, HTTP Trigger in particular, to integrate with Flow.

As a Marketing Staff, I Want to …

Let’s say there is someone from a marketing department. They want to search all Twitter posts with a hashtag, #ausopen, for example and those posts are fetched to their marketing Slack channel. This can be easily accomplished by using a pre-defined template.

We can easily set the hashtag they want to follow and Slack channel to fetch like:

This is all set! Too easy! Now, we are with the Free plan, this Flow runs every five minutes. If we want to run the flow more frequently, we should upgrade the plan to paid ones like Flow Plan 1 (runs every 3 mins) or Flow Plan 2 (runs every minute). Once the flow runs, the marketing channel in Slack will receive all tweets like:

We’ve so far created a Flow item as an example.

As a …, I Want to Handle those Tweets in a Different Way

Probably, the marketing staff needs more sophisticated analysis by storing those tweets into database or want to do something else that pre-defined actions/triggers don’t support out-of-the-box. In this case we can introduce HTTP Trigger Functions to do so. Let’s create an HTTP Trigger Function.

Of course, we should implement more complex logic in the function. However, this is just an example, so we only log how Flow passes the data to Azure Function for now. When the function is ready like above, we know its endpoint URL like

Copy this endpoint URL for Flow. Now we need to modify the existing Flow item like:

When a new tweet with the hashtag #ausopen is found, the entire tweet object is passed to Azure Functions through the POST method, then the tweet is posted to the Slack channel. Wait for up to five minutes (we’re with the Free Plan!)

Slack channel has finally been updated.

This is the log from Flow:

And this is the log from Azure Functions:

So far, we have integrated Azure Functions (HTTP Trigger) with Microsoft Flow so that we can do more complex jobs through it. The code used in this post was very simple, but depending on the complexity of requirements, the function will handle jobs in more sophisticated way.

Adding YAML Settings into ASP.NET Core Apps

Unlike traditional ASP.NET web apps using web.config for configuration, ASP.NET Core apps supports various file formats for it. When we actually see the source codes, configuration supports XML, JSON, INI, Azure Key Vault, in-memory collection, command line arguments and environment variables. However, another popular format, YAML is not officially supported in ASP.NET Core at the time of writing. In this post, we are going to walk through how we can import YAML settings file to support ASP.NET Core web application.

You can find sample codes used in this post at here

Analysis of ConfigurationBuilder

When we first create a new ASP.NET Core application project, no matter it is a web app or an API app, we can always see how ConfigurationBuilder is implemented.

As we can see above, appsettings.json is included as a default, followed by secret settings, if it’s a development mode, then environment variables. If we want, we can add an XML file by adding builder.AddXmlFile("appsettings.xml"); or an INI file by adding builder.AddIniFile("appsettings.ini");, or others from various sources. In this case, we MUST make sure that the order of adding settings is very important. The settings defined in the latter file always overwrite the settings previously defined. For example, if JSON settings is loaded first then XML settings is loaded later, if a same key exists in both settings files, the value from the XML settings will always be considered.


As YAML settings is not supported out-of-the-box, we need to implement an extension. As there’s already a NuGet package for this extension, we will just use it. Here are sample appsettings.json and appsettings.yml files:

Now, we’re modifying the existing Startup.cs file to load YAML settings.

The builder.AddYamlFile() method has been added right after the builder.AddJsonFile() method. Therefore, we are expecting the clientId value will be FROM appsettings.yml. Let’s check it out. First of all, we need to inject the settings into a controller. Here’s a code bits to deserialise the settings into a strongly-typed instance and inject into the built-in IoC container.

Now, we need to resolve that instance from the controller level, which is a typical DI stuff.

We’re all set. Let’s run the app and see how it’s going. Can we see the result like below?

Order is Important!

As we’ve dealt above, the latter settings takes precedence for the same key. Now, let’s change between JSON settings and YAML one the other way around like:

Then try the web app again. What can we expect?

So far we have looked how to import/load YAML settings into our ASP.NET Core web apps. Can we use YAML for our ASP.NET Core web app now? Yes, we can!

Testing Precompiled Azure Functions

Azure Functions has recently added a new feature that allows precompiled assembly to run functions. This gives us a great confidence with regards to unit testing. In this post, we are walking through how to unit test functions with ease, like which we do tests everyday.

The sample code used in this post can be found at HERE.

Function without Dependency

We’re not digging down precompiled function too much as it’s on the document. Let’s have a quick look at the HTTP trigger function code:

Nothing special. Now, we’re writing a test code for this function using xUnit and FluentAssertions.

How does it look like? It’s the same unit test code as what we do everyday. Let’s move on.

Function with Dependency

As I wrote Managing Dependencies in Azure Functions on the other day, dependency management is a bit tricky for Azure Functions due to its static nature. Therefore, we should introduce Service Locator Pattern for dependency management (or injection). Here’s the sample function code:

As we can see the code above, value is retrieved from the service locator instance. Of course, this is just a simple implementation of service locator pattern (If we need more sophisticated one, we should consider an IoC container library like Autofac). And here’s the poorman’s service locator:

Let’s see the test code for the function with dependencies. With the service locator, we can inject mocked object for unit testing, which is convenient for developers. In order for mocking, we use Moq in the following test code.

We create a mocked instance and inject it into the service locator. Then the injected value (or instance) is consumed within the function. How different is it from the everyday testing? There’s no difference at all. In other words, implementing a service locator gives us the same development experiences on Azure Functions, from the testing point of view.

I wrote another article for testing a few months ago, using ScriptCs. This used to be one approach, when Azure Functions didn’t support the precompiled assemblies. Now, we have precompiled functions supported. Therefore, I hope this post would be useful to design functions with better testability.

Is Azure Functions over Web API Beneficial?

Whenever I meet clients and give a talk about Azure Functions, they are immediately interested in replacing their existing Web API features with Azure Functions. In this post, I’d like to discuss:

  • Can Azure Functions replace Web API?
  • Is it worth doing?

It would be a good idea to have a read through this article, Serverless Architectures, before starting.

HTTP Trigger Function == Web API Action

One of characteristics of Serverless Architecture is “event-driven”. In other words, all functions written in Azure Functions are triggered by events. Those events of course include HTTP requests. From this HTTP request point of view, both HTTP trigger function and Web API action work exactly the same way. Let’s compare both codes to each other:

How do both look like? They look pretty similar to each other. Both take an HTTP request, process it and return a response. Therefore, with minor modification, it seems that Web API can be easily migrated to Azure Functions.

HTTP Trigger Function != Web API Action

However, life is not easy. There are some major differences we should know before migration:

Functions are always static methods

Even though Azure Functions are extensions of Azure WebJobs, each function has a static modifier by design, unlike Azure WebJobs can be without the static modifier.

Actions of Web API, by the way, don’t have the static modifier. This results in a significant architectural change during the migration, especially with dependency injection (DI). We will touch it later.

Functions always receive HttpRequestMessage instance as a parameter

Within the HTTP request/response pipeline, a Web API controller internally creates an HttpContext instance to handle data like headers, cookies, sessions, querystrings and request body (of course querystrings and request body can be handled in a different way). The HttpContext instance works as an internal property so any action can directly access to it. As a result, each action only passes necessary details as its parameters.

On the other hand, each function takes a different HTTP request/response pipeline from Web API, which passes the HttpRequestMessage instance to the function as a parameter. The HttpRequestMessage instance only handles headers, querystrings and request body. It doesn’t look after cookies or sessions. This is the huge difference between Web API and Azure Functions in terms of stateless.

Functions define HTTP verbs and routes in function.json

In Web API, we put some decorators like HttpGet, HttpPost, HttpPut, HttpPatch and HttpDelete on each action to declare which HTTP verbs take which action, by combining with the Route decorator.

On the other hand, each function has a definition of HTTP verbs and routes on function.json. With this definition, different functions having the same route URI can handle requests based on HTTP verbs.

Functions define base endpoint URI in host.json

Other than the host part of URI, eg), the base URI is usually defined on the controller level of Web API by adding the Route decorator. This is dead simple.

However, as there’s no controller on Azure Functions, it is defined in host.json. Default value is api, but we can remove or redefine to others by modifying host.json.

While function.json can be managed at the function level through GUI or editor, unfortunately it’s not possible to edit host.json directly in the function app. There’s a workaround using Azure App Service Editor to modify host.json, by the way.

Functions should consider service locator pattern for dependency management

There are many good IoC container libraries for Web API to manage dependencies. However, we have already discussed this in my previous post, Managing Dependencies in Azure Functions, that Service Locator Pattern should be considered for DI in Azure Functions and actually this is the only way to deal with dependencies for now. This is because every Azure Function has the static modifier which prevents us from using the same way as the one in Web API.

We know different opinions against service locator patterns for Azure Functions exist out there, but this is beyond our topic, so we will discuss it later in another post.

Is Azure Functions over Web API Beneficial?

So far, we have discussed what are same and what are different between Web API and Azure Functions HTTP Trigger. Back to the initial question, is it really worth migrating Web API to Azure Functions? How does your situation fall under any of below?

  • My Web API is designed for microservices architecture: Then it’s good to go for migration to Azure Functions.
  • My Web API takes long for response: Then consider Azure Functions using empty instance in App Service Plan because it costs nothing more. Consumption Plan (or Dynamic Service Plan) would cost too much in this case.
  • My Web API is refactored to use queues: Then calculate the price carefully, not only price for Azure Functions but also price for Azure Service Bus Queue/Topic and Azure Storage Queue. In addition to this, check the number of executions as each Web API is refactored to call one Http Trigger function plus at least one Queue Trigger function (two executions in total, at least). Based on the calculations, we can make a decision to stay or move.
  • My Web API needs a significant amount of efforts for refactoring: Then it’s better to stay until it’s restructured and suitable for microservices architecture.
  • My Web API is written in ASP.NET Core: Then stay there, do not even think of migration, until Azure Functions support ASP.NET Core.

To sum up, unless your Web API requires a significant amount of refactoring or written in ASP.NET Core, it surely is worth considering migration to Azure Functions. It is much easier to use and cost-effective solution for your Web API.

Debugging Azure Functions in Our Local Box

Because of the nature of Azure Functions – Serverless Architecture, it’s a bit tricky to run it on my local machine for debugging purpose.

There is an approach related to the issue in this post, Testing Azure Functions in Emulated Environment with ScriptCs. According to the article, we can use ScriptCs for local unit testing. However, the question on debugging still remains because testing and debugging is a different story. Fortunately, Microsoft has recently released Visual Studio Tools for Azure Functions. It’s still a preview stage, but worth having a look. In this post, I’m going to walk-through how to debug Azure Functions within Visual Studio.

Azure Functions Project & Templates

After we install the toolings, we can create an Azure Functions project.

That gives us the same development experiences. Pretty straight forward. Once we create the new project, we can find nothing but only a couple of .json files   appsettings.json and host.json. The appsettings.json is only used for our local development, not for the production, to hook up the actual Azure Functions in the cloud. We are going to touch this later in this post.

Now let’s create a function in C# codes. Right mouse click on the project and add a new function.

Then we can see a list of templates to start with. We just select from HttpTrigger function in C#.

Now we have a fresh new function.

As we can see, we have a couple of another .json files for settings. function.json defines input and output, and project.json defines list of NuGet packages to import, same as what .NET Core projects do.

We’ve all got now. How to debug the function then? Let’s move on.

Debugging Functions – HTTP Trigger

Open the run.csx file. Set a break point wherever we want.

Now, it’s time for debugging! Just punch F5 key. If we haven’t installed Azure Functions CLI, we will be asked to install it.

We can manually install CLI through npm by typing:

Once the CLI is installed, a command prompt console is open. In the console, it shows a few various useful information.

  • Functions in the debugging mode only takes the 7071 port. If any of application running in our local has already taken the port, it would be in trouble.
  • The endpoint of the Function is always http://localhost:7071/api/Function_Name, which is the same format as the actual Azure Functions in the cloud. We can’t change it.

Now it’s waiting for the request coming in. It’s basically an HTTP request, we can send the request through our web browser, Postman or even curl.

Any of request above is executed, it will hit the break point within Visual Studio.

And the CLI console prints out the log like:

Super cool! Isn’t it? Now, let’s do queue trigger function.

Debugging Functions – Queue Trigger

Let’s create another function called QueueTriggerCSharp. Unlike HTTP triggered functions, this doesn’t have endpoint URL (at least not publicly exposed) as it relies on Azure Storage Queue (or Azure Service Bus Queue). We have Azure Storage Emulator that runs on our dev machine. With this emulator, we can debug our queue-triggered functions.

In order to run this function, we need to setup both appsettings.json and function.json

Here’s the appsettings.json file. We simply assign UseDevelopmentStorage=true value to AzureWebJobsStorage for now. Then, open function.json and assign AzureWebJobsStorage to the connection key.

We’re all set. Hit F5 key see how it’s going.

Seems nothing has happened. But when we see the console, certainly the queue-triggered function is up and running. How can we pass the queue value then? We have to use the CLI command here. If environment variable doesn’t recognise func.exe, we have to use the full path to run it.

Now we can see the break point at Visual Studio.

So far, we’ve briefly walked through how to debug Azure Functions in Visual Studio. There are, however, some known issues. One of those issues is, due to the nature of .csx format, IntelliSense doesn’t work as expected. Other than that, it works great! So, if your organisation was hesitating at using Azure Functions due to the lack of debugging feature, now it’s the time to play around it!

Implementing HTTP Request Handler on ASP.NET Core Applications

ASP.NET WebForm or MVC applications rely on global.asax to process HTTP request pipelines. Within global.asax, each HTTP request goes through declared HTTP modules and HTTP handlers based on events. On the other hands, ASP.NET Core applications use OWIN middlewares. Actually, those middlewares now take care of what HTTP modules and HTTP handlers do. In this post, we are going to implement an HTTP request handler on a ASP.NET Core application.

Why Does It Matter?

Single Page Applications (SPA) is now a trend of web application development. SPA only contains UI logics and all other business logics are processed by calling APIs. Calling APIs through AJAX is not a problem. For example, if we use jQuery, typical AJAX call will look like:

If we need an API key for the call, the AJAX call might look like:

We might be feeling agitated here because auth key and API key are exposed within the JavaScript block, which is not we want. In this case, we usually implement API proxy (or API facade or whatever we call) so that we hide that sensitive information from the UI side. Instead, the proxy takes care of those details. Well, how can we implement the proxy then? We can implement this proxy through MVC controllers or middlewares. The good thing with middlewares to handle this is that WE DON’T NEED CONTROLLERS AT ALL. Let’s have a look.


The main differences between HTTP modules and HTTP handler are:

  • HTTP modules process requests and pass them to another modules.
  • HTTP handlers process requests and return their responses to browsers.

As middlewares in ASP.NET Core take care of both HTTP modules and HTTP handlers, implementation becomes a lot easier and simpler. Here’s a basic middleware looking like:

And, in order to easily use this middleware at Startup.cs, we can just create an extension method like:

And this extension method is placed into the Configure method of Startup.cs like:

Within the OWIN pipeline, middlewares are invoked by an order where they are declared. Therefore, MyMiddleware is invoked after the previous middleware then passes HttpContext instance to the next middleware for further processing. Here’s the clue. If we want to implement the middleware as an HTTP handler, we simply don’t run the this._next.Invoke(context) method so that all HTTP requests complete processing at this point. Let’s make a working example.

All codes used in this post here can be found at:

HTTP Request Header Handler Middleware

We don’t need MVC controller for our ASP.NET Core application any more because the middleware takes all AJAX requests, put some additional header and pass the requests to API server. Therefore, we can simply remove MVC middleware from the Startup.cs and add HttpRequestHeaderHandlerMiddleware into it.

Then, implement HttpRequestHeaderHandlerMiddleware like:

As we can see above, it processes the request and sends HttpContext back with response. This perfectly works as API proxy, without needing controllers. Let’s go further.

Middleware with Options Pattern

The potential problem of HttpRequestHeaderHandlerMiddleware written above is that all custom headers are hard-coded. If we add/update/delete header values, we have to update the code. Fortunately, ASP.NET Core provides Options Pattern. This is basically for dependency injection for configuration values that are declared within appsettings.json or environment variables. We can use this pattern for our middleware implementation with additional extension methods.

We have HttpRequestHeaderHandlerMiddlewareOptons and this will be injected to HttpRequestHeaderHandlerMiddleware by calling Options.Create(options) method, which creates IOptions instance. Here’s another extension method to declare options with lambda expressions.

Once it’s done, the HttpRequestHeaderHandlerMiddleware needs to be updated to accept the options instance as a parameter.

Now we can use options within our middleware. Those options can be defined within appsettings.json file, populated as a strongly-typed instance and injected to the middleware like:

So far, we have implemented a middleware as an API proxy to capture all HTTP requests, put extra header information into it and process it. With this approach, our SPA backed by ASP.NET Core would be much simpler and light-weighted.

Managing Dependencies in Azure Functions

Just before the Connect(); event, Azure Functions has become GA. Now more and more developers and IT pros are interested in it. One of the main attractions of using Azure Functions is, as a developer using C# codes, we can directly import existing private assemblies into Functions. In other words, we can easily migrate our existing applications to Azure Functions with minimal changes!

However, as we all know, migration is not that easy, especially if a huge architectural change is required. Once of the biggest challenges for the migration is probably “Managing Dependencies”. In this post, we are going to have a look which approach would be suitable for us to migrate applications smoothly.

We can find the source codes used in this post here:

Azure Function Structure

Let’s see the basic function structure. Here’s a function code when we create a manual trigger function:

What can we see here? That’s right. It’s a static method! That simply means our existing IoC container won’t fit here, if we use an IoC container for dependency management. So, what can we do here? We now need to consider a service locator pattern.

Autofac and CommonServiceLocator

If we use Autofac for our application’s dependency management, we need to create a service locator object using Autofac.Extras.CommonServiceLocator. Let’s see some code bits:

First of all, like what we are doing with Autofac, we just add dependencies using builder.RegisterType(). Then, we create an AutofacServiceLocator instance and put the instance to the service locator instance. That’s it! Let’s create a function.

Azure Functions with Service Locator

We don’t need to follow the whole step, but as a best practice that Azure Functions team suggests, we’re putting a private assemblies into the Shared folder using KUDU.

And create a .csx file within the Shared folder to create the service locator instance.

Now we have a static locator instance. We all set. Let’s create a function using this instance.

If we run this function, we get the result as expected.

This also works in an async function:

So far, we have a brief look how the service locator pattern works for our Azure Functions to manage dependencies. Migration to Azure Functions from our existing application wouldn’t be that easy, of course. However, we still use existing private assemblies as long as we introduce the service locator pattern for dependency management. Service locator pattern might be old-fashioned, but surely it’s working. There might be a better solution for managing dependencies. If you guys find anything better, let’s discuss here!

Deserialising .NET Core Configuration Settings

With System.Configuration.dll, we can add custom configSections into either App.config or Web.config files so that we can utilise strongly-typed configuration objects. On the other hand, .NET Core applications have replaced those App.config or Web.config with appsettings.json, which is more convenient for developers to use, especially for dependency injection (DI). In this post, we are going to walkthrough how we can deserialise the appsettings.json for DI purpose.


When we create an ASP.NET Core web application, we have a basic appsettings.json file looking like:

This is loaded up and built as an IConfiguration instance in Startup.cs. If we want to access to values, we simply call like:

This is good for fast application prototyping purpose, in general. However, if we need strongly-typed objects for those configurations, this is not ideal. How can we get the strongly typed objects then? Let’s have a look.

.NET Core RC1/RC2 Applications

Microsoft.Extensions.Configuration used to provide an extension method called Get(string key). With this method, we can easily deserialise appsettings.json object to an object of type T. Let’s say we have the AuthenticationSettings class representing the authentication section in appsettings.json. This is a sample code:

Now we have the auth instance to be injected wherever we want by:

.NET Core Applications

In .NET Core applications, unfortunately, the Get(string key) extension method has been removed. Instead, Microsoft.Extensions.Configuration.Binder provides another extension method called Bind(object instance). This actually binds an instance with the configuration value. Therefore, in order to have the same development experience as RC1/RC2, we should implement an extension method by ourselves like:

By implementing this extension method, we do the same approach as what we used to do in RC1/RC2 like above.

So far, we have briefly looked how we can deserialise appsettings.json on .NET Core applications for injection use. This would be useful for our robust application development.


Testing Azure Functions in Emulated Environment with ScriptCs

In the previous post, Azure Functions Deployment Strategies, we have briefly looked several ways to deploy Azure Functions codes. In this post, I’m going to walk through how we can test Azure Functions codes on developers’ local machine.

Mocking and Asserting on ScriptCs

We need to know how to run test code scripts using ScriptCs. We’re not going too much details how to install ScriptCs here. Instead, we assume that we have ScriptCs installed on our local machine. In order to run test codes, mocking and asserting are crucial. There are ScriptPack NuGet packages for mocking and asserting, called ScriptCs.Moq and ScriptCs.FluentAssertions. If we use those packages, we can easily setup unit testing codes, with similar development experiences. Let’s have a look.

First of all, we need to install NuGet packages. Make sure that ScriptCs doesn’t yet support NuGet API version 3 at the moment of this writing, but it will support sooner or later based on their roadmap. In other words, we should stay on NuGet API version 2. This is possible by creating a scriptcs_nuget.config file in our script folder like:

Then run the command below on our Command Prompt console, to install ScriptCs.Moq.

Now, create a run.csx file like:

Run the following command and we’ll be able to see mocked result as expected.

This time, install ScriptCs.FluentAssertions for assertions.

This is the script for it:

We expected world but the value was hello, so we can see the message like:

Now, we know how to run test codes on our local machine using ScriptCs. Let’s move on.

Emulating Azure Functions on ScriptCs

There is no official tooling for Azure Functions running in a developer’s local machine yet. However, there is a script pack called ScriptCs.AzureFunctions that runs on ScriptCs. With this, we can easily emulate Azure Functions environment on our local dev machine. Therefore, as long as we have a running Azure Functions code, ScriptCs.AzureFunctions wraps the code and run it within the emulated local environment.

Azure Functions Code with Service Locator Pattern

This is a sample Azure Functions script, run.csx.

When you look at the code above, you might have found that we use a Service Locator Pattern. This is very important to manage dependencies in Azure Functions. Without a service locator, we can’t properly test Azure Functions codes. In addition to this, Azure Functions only supports a static method so the service locator instance is instantiated with the static accessor.

Here are the rest bits of the poorman’s service locator pattern.

Emulation Code for Azure Functions

Now, we need to write a test code, test.csx. Let’s have a look. This is relatively simple.

  1. Import run.csx by using the #load directive.
  2. Arrange parameters, variables and mocked objects.
  3. Run the Azure Functions code.
  4. Checks the expected result.

If we use ScriptCs.FluentAssertions package here, the last assert part would be much nicer.

Now run the test code:

Now, we have an expected result in the emulated environment.

So far, we’ve briefly walked through how we can emulate Azure Functions on our development environment. For testing, Service Locator Pattern should be considered. With ScriptCs.AzureFunctions, testing would be easily performed in the emulated environment. Of course this is not a perfect solution but surely it’s working. Therefore, it would be useful until the official tooling is released. If our build server allows ScriptCs environment, this emulation environment can be easily integrated so that we can perform testing within the build and test pipeline.