Summary
What | The following is an example of how to ingest mock data from a json file into a .NET application through app configuration |
Why | When building an app iteratively, or just doing a proof-of-concept spin-up, we can use mock data to build out the app; this approach gets to done faster |
How | The approach uses .NET 7, the web host builder, and a json file loaded as part of the app’s configuration. We can use this approach in any .NET app using Microsoft’s chained configuration — apps with web host builder, the generic host builder, or just using ConfigurationManager |
This is not the only approach; mock data can be hard-coded a number of ways, including an in-memory collection add to the configuration. | |
More | If you want to understand Microsoft’s chained configuration approach, I have an article and code you can dive into |
In later articles in this series, this demo app will be explored in more depth |
Scaffold the App
First, spin up a scaffolded (from a template) .NET app. In this example, I spun up an ASP.NET Core Web API.
The Mock Data as Json File
Then, we represent the data in a simple json file:
Pull Json into the App Configuration
With that in place, next, in the Program.cs
after the creation of the builder and before services configuration, we add the json file to the ConfigurationManager:
Typically, a .NET app may have `appsettings.json` or even corresponding files `appsetings.{environment}.json` that are applied almost at the end of the chained configuration (Azure settings, if available, will override appsettings).
Model for Data
Add a model for representing the json data array elements, then access the data wherever we want from the configuration:
Pingback: MinimalAPI with .NET 7 and OpenAPI: A Tutorial - Code Onward