Skip to main content

Using ConfigCat Feature Flags in ASP.NET Core Web API

· 9 min read
Emil Kovačević

Many people think of the Internet as a place where they can find information or communicate with others. However, the Internet is far more than that, it is also growing with its capabilities. Holding data resources that support the lives of billions of people around the world.

One way to transfer data on this great thing we call the Internet, while having a good development pipeline and maintaining security, is to construct a Web API.

Feature flags in net core web API cover photo

The sample application

Let's say you have a database of your users, and you want to launch a new feature in your Web API. You want to release it first to your paying users. Later, maybe release it to everyone. But how, how can you do that? How to ensure that only a certain user group gets the new feature?

I'll showcase this with ConfigCat's feature flag system in an ASP .NET Core Web API. ConfigCat is a developer-centric feature flag service with unlimited team size, awesome support, and a reasonable price tag.

The API will produce a JSON Object that holds a list of Car Manufacturers and their daily stock movement. Some JSON Object key/value pairs will be public while others private, depending on the feature flag setting (ON/OFF) and user credentials. To accomplish this, I will leverage ConfigCat's user targeting system, and target premium accounts.

You can find the source code on GitHub.

What is a Web API

To understand what a Web API is, let's start by defining an API.

An API (application programming interface) is an interface that provides a set of hidden functions to the user where the underlying mechanism of that function talks to the system. These functions can be CRUD (create, read, update, delete) operations or any other operations like pagination, search, or even system reboot.

In essence, an API is an interface which acts as a software intermediary that allows a surface application to talk with the underlying system.

Defining a Web API

A Web API is an API that is used on the Internet. Here you have a client application and a server where the data is passed around through HTTP (hypertext transfer protocol) requests. Here the client calls a specific portion of the API.

The calls that make up the API are also known as subroutines, methods, requests, or endpoints.

What is a feature flag?

A feature flag is a unique boolean that defines an allowable configuration for an application. Each feature flag has its own set of rules, which often differ from application to application.

For example, a stock market app may have different rules for different features. These rules are known as policies and are configured by the development team. A policy defines what actions are allowed in specific situations and can even define allowed outcomes. This way, developers can tightly control the actions their users are allowed to perform on their apps.

Building a .NET Core Web API


Creating a flag

  1. Sign up for a free ConfigCat account.

  2. Create a feature flag name in the Name for hoomans field

example: name for Hoomans : MyFeatureFlag

The name for programs will be automatically generated, and that name is going to be used in the API application.

  1. Click on the ADD FEATURE FLAG button

new feature flag

Configuring the flag

  1. Add a new targeting rule
  2. Set the users' target to custom
  3. Set the custom attribute to "account"
  4. Set the comparator value to IS ONE OFF (hashed)
  5. Set the comparison value to "Premium"
  6. Leave the All other users, serve toggle to off, and just keep the one in the if statement on.
  7. Save and publish the changes

You can have a look at the image below for reference.

You can learn more about ConfigCat's targeting here.

configcat dashboard

Creating the Project

  1. Open Visual Studio and Create a New Project
  2. Select the ASP .NET Core Web API as the type of the project
  3. Name the project
    • I named mine "ConfigCatProject"
    • as for the Solution name, I named mine "ConfigCatSolution"
  4. Leave the additional configuration as default, like in the picture below,
  5. Click Create

visual studio setup

Adding ConfigCat to the application

In the Visual Studio top menu, navigate to:

  • Tools/Nuget Package Manager/Manage Nuget Packages for Solution. A window should pop up with the installed plugins.
  • In the search bar, type in "configcat" and click on the Browse tab. Find the ConfigCat.Client and Install it as shown in the picture below.


Creating the API

I will start by registering ConfigCatClient in my Program.cs file as a singleton object. This will create a new instance of ConfigCatClient that can be used anywhere in the application.

builder.Services.AddSingleton<IConfigCatClient>(sp =>
var client = new ConfigCatClient(options =>
options.SdkKey = "<YOUR SDK KEY>";
options.PollingMode = PollingModes.AutoPoll(pollInterval: TimeSpan.FromSeconds(5));
} );

return client;

In the code above, you can see that ConfigCatClient is easily added to my project with a builder service. Within this service, I defined ConfigCatClient as a service provider and passed in the ConfigCat SDK key.

By default, the ConfigCat SDK downloads and stores the latest values automatically every 60 seconds. This can be overwritten by setting a PollingMode to another interval.

You can learn more about ConfigCat's .NET / .NET Core SDK and the polling modes here.

Creating the controller

  1. In the Solution Explorer, go to the Controllers folder, delete the WeatherForecastController file
  2. Right-click on the "Controllers" folder
  3. Go to Add/Controller... and click on it
  4. Select the MVC controller - empty and add it to your project, I named mine CarStocksController.

Injecting the ConfigCat Client into the controller

public class CarManufacturerStocksController : ControllerBase
private readonly IConfigCatClient configCatClient;

public CarStocksController(IConfigCatClient configCatClient)
this.configCatClient = configCatClient;


I defined the API endpoint as /api/CarManufacturerStocks/24h/usd, where I am simulating a REST Uniform Identifier on manufacturer stock market - 24h trading in USD currency.

Creating the HTTP Get Method

I will use the HTTP GET method in the controller to create a data set for the JSON Object.

For demo purposes, I will hard code a user. Usually, the user data is pulled from a server back-end.

To retrieve the latest values from the ConfigCat Client, I defined a simple boolean variable under the user object.

public IEnumerable<CarmanufacturerStock> Get()
// Defining a user

var userObject = new User("<Some UserID>")
Email = "[email protected]",
Country = "USA",
Custom = new Dictionary<string, string>
{"Account", "Premium"},
bool isFlagOn = this.configCatClient.GetValue("myfeatureflag", false, userObject);

Creating random data to generate a JSON Object

I opted to create a random data set to generate a JSON Object, however, this data would usually be pulled from some external service or server.

I am going to return a random set of 5 car manufacturer stocks with IEnumerable interface.

Note: IEnumerable is best to query data from in-memory collections like List, Array etc. IEnumerable doesn't support adding or removing items from the list at run time.

return Enumerable.Range(1, 5).Select(index => new CarStocks {
ID = index,
Date = DateTime.Now.AddDays(index),
CarBrand = CarBrands[Random.Shared.Next(CarBrands.Length)],
StockPrice = Random.Shared.Next(2, 350),
Volume24h = Random.Shared.Next(20000000, 780000000),

// we are conditionaly injecting data in JSON depending on the flag value
Movement = isFlagOn ? Stock() : null

You can see that in the Movement key I used a ternary operator to show data depending on the flag status. In the code below you can see the code that will be executed as the new feature.

static Object[] Stock () {
Object[] stock = {
new { key = "change", value = Random.Shared.Next(-20, 30).ToString()},
new { key = "multiplier", value = Random.Shared.Next(0, 20).ToString()},
new { key = "spread", value = Random.Shared.Next(0, 100).ToString()}
return stock;

Creating the CarManufacturerStock Class

In the Solution Explorer, rename the WeatherForecast.cs file to CarManufacturerStock. Open the file and replace it with the code below.

namespace ConfigCatAPIDemo
public class CarManufacturerStock
public DateTime Date { get; set; }

public int ID { get; set; }

public string? CarBrand { get; set; }

public int StockPrice { get; set; }

public int Volume24h { get; set; }

public Object[]? Movement { get; set; }

You can see that the Object[]? is nullable with the ? tag in case the flag is set to OFF.

Testing the application

I will use SwaggerUI, which came with the starting project to interact with the Web API.

To see how the code works, start the application with the green play button on top of the Visual Studio IDE. When the code compiles successfully, a browser window will open. The SwaggerUI should show you a generated page where you can test the application.


Click on the Try it out button and then the Execute button, the response will be returned to the page with movement data.

"date": "2022-11-07T16:32:10.2919244+01:00",
"id": 1,
"carBrand": "Hyundai",
"stockPrice": 94,
"volume24h": 383345006,
"movement": [
"key": "change",
"value": "-9"
"key": "multiplier",
"value": "17"
"key": "spread",
"value": "61"
}, ... ]
  • To toggle the feature on or off, open the ConfigCat dashboard and toggle the flag.
  • Wait the amount the seconds that you entered in the "polling mode".
  • Re-Execute the Get method in SwaggerUI. Now the response will return a JSON Object where the movement value is hidden (null).
"date": "2022-11-07T16:13:41.8473912+01:00",
"id": 4,
"carBrand": "Abarth",
"stockPrice": 193,
"volume24h": 74446081,
"movement": null

You can also see the Raw JSON format by manually typing in the API path in the browser search bar.

Like this: https://localhost:<YOUR-PORT-NUMBER>/api/CarManufacturerStocks/24h/usd

Feel free to experiment with the code.

In summary, integrating ConfigCat's feature flags into ASP DOT NET CORE API is super easy and doesn't require much effort.


If you would like to see how to use ConfigCat in other applications/programming languages, check out configcat-labs.

To learn more about ConfigCat's flags, visit the docs.

All ConfigCat SDKs have their own GitHub repository with sample applications, you can find them here.

Stay on top of the latest posts and announcements from ConfigCat on Twitter, Facebook, LinkedIn, and GitHub. Deploy any time, release when confident.