Custom Middlewares in ASP.NET Core: JSON Processing for Multiple Models

Developing a portfolio web application backend using .Net Core, I considered fetching JSON data from a remote location. It was simple to put JSON on a remote URL and use the endpoints in my application to download it. It also provided me with a quick way to edit my JSON and reflect updates in the application without the need to work on the application itself.

To make the JSON data more manageable, I split the large JSON data into smaller JSONs so that I could be able to edit each portion of portfolio data separately.


Article content
Large Profile data split.

These JSONs are required to be parsed into models so that can be used in the application. Let's have models for these JSONs in the project as shown.


Article content
Model Classes

For more clarity let's check the contents of our Introduction Model class and its JSON data.

The JSON data.

{
  "Name": "Muaaz Abbasi",
  "TopSkills": [
    "Full Stack",
    ".Net Core",
    "Unity",
    "Azure",
    "Multiplayer Online"
  ],
  "Mobile": "+923334886927",
  "Email": "muaazabbasi@gmail.com",
  "Location": "Lahore, Punjab, 54000, Pakistan.",
  "LinkedIn": "www.linkedin.com/in/muaaz-abbasi-solution-architect",
  "TopRoles": [
    "Solution Architect",
    "Technical Lead",
    "Technical Project Manager"
  ],
  "Description": "With extensive experience in C# technologies, including .NET Core and Unity, I specialize in architecting scalable software solutions. My background in Azure cloud computing drives my passion for designing cloud-native applications. I leverage cutting-edge tools and frameworks to deliver innovative, high-performance, and secure solutions, while continually updating my skills to meet industry standards."
}        

and the Model class

namespace MyPortfolio.Models
{
    public class Introduction
    {
        public  string Name { get; set; }
        public  List<string> TopSkills { get; set; }
        public  string Mobile {  get; set; }
        public  string Email { get; set; }
        public  string Location { get; set; }
        public  string LinkedIn { get; set; }
        public  List<string> TopRoles { get; set; }
        public  string Description { get; set; }
    }
}        

Now that we have our data and the model, we should have a unified class in our application which can provide us with the parsed data. Let's create the Class JsonDataStore.

using MyPortfolio.Models;
namespace MyPortfolio
{
    public class JsonDataStore
    {
        public List<Awards> Awards { get; set; } = new List<Awards>();
        public List<Certifications> Certifications { get; set; } = new List<Certifications>();
        public List<Courses> Courses { get; set; } = new List<Courses>();
        public Education Education { get; set; } = new Education();
        public List<Experience> Experience { get; set; } = new List<Experience>();
        public Introduction Introduction { get; set; } = new Introduction();
        public List<Linguistics> Linguistics { get; set; } = new List<Linguistics>();
        public List<Projects> Projects { get; set; } = new List<Projects>();
        public List<Skills> Skills { get; set; } = new List<Skills>();
    }
}         

We now have our JSON data, the model and the class that we could use to get the parsed data from let's write our custom middleware to download and parse the JSON data into the model. We can have separate custom middleware for each model.


Article content
Our Custom Middlewares

What does our middleware code look like? Let's see the custom middleware class for our Introduction data.

using MyPortfolio.Models;
using System.Text.Json;
namespace MyPortfolio.CustomMiddlewares
{
    public class IntroductionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly HttpClient _httpClient;
        private string URL = "XXXXXXXXXXXXXXXXXX/Introduction.json";

        public IntroductionMiddleware(RequestDelegate next)
        {
            _next = next;
            _httpClient = new HttpClient();
        }

        public async Task InvokeAsync(HttpContext context, JsonDataStore dataStore)
        {
            // Download Model JSON data
            var response = await _httpClient.GetAsync(URL);
            if (response.IsSuccessStatusCode)
            {
                string jsonContent = await response.Content.ReadAsStringAsync();
                var modelData = JsonSerializer.Deserialize<Introduction>(jsonContent);
                dataStore.Introduction = modelData;
            }

            // Call the next middleware in the chain
            await _next(context);
        }
    }
}        

After implementing our middleware, it is time to register them in the sequence we want such as shown.


Article content
Registering our data store and custom middlewares.

When our application is run the JSONs would be downloaded and parsed in their respective models. Our JsonDataStore is also available to be used to get data in our application.

At first we decided to split our large Json into smaller ones and created their respective model classes. We planned to use custom middleware to download and parse the data asynchronously and implemented our custom middleware classes. The data store class provided us a way to access the parsed data in our application.


To view or add a comment, sign in

More articles by Muaaz Abbasi

Insights from the community

Others also viewed

Explore topics