Turn your content types into strongly typed models
Improve your development experience by using strongly typed models based on your Kontent.ai content types.
Life without strongly typed models
When getting content directly from the Delivery REST API, you receive content items as JSON objects. Your app then needs to parse the JSON to display your content. For example, to access the Headline element in a content item, you’d use a notation like thisresponse.data.item.elements.headline.value
.
In real-life scenarios, this approach might be cumbersome because it requires you to remember the JSON structure of your content items, and the codenames of your elements, types, languages, and other entities.
To make this easier, use a Delivery SDK (the JS versionUse strongly typed models
This practice has several advantages:- type safety during compile-time
- convenience (IntelliSense remembers content type properties for you)
- support of type-dependent functionalities
- All elements defined within a specific content type
- System fields such as type, workflow, language, and more
// This code was generated by a kontent-generators-net tool
// (see https://github.com/kontent-ai/model-generator-net).
//
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
// For further modifications of the class, create a separate file with the partial class.
using System;
using System.Collections.Generic;
using Kontent.Ai.Delivery.Abstractions;
namespace KontentAiModels
{
public partial class Homepage
{
public const string Codename = "homepage";
public const string BodyTextCodename = "body_text";
public const string HeadlineCodename = "headline";
public const string PictureCodename = "picture";
public IRichTextContent BodyText { get; set; }
public string Headline { get; set; }
public IEnumerable<IAsset> Picture { get; set; }
public IContentItemSystemAttributes System { get; set; }
}
}
Generate models
We recommend that you generate the models using the .NET model generator
.
dotnet tool install -g Kontent.Ai.ModelGenerator
KontentModelGenerator --projectid 8d20758c-d74c-4f59-ae04-ee928c0816b7 --withtypeprovider true --structuredmodel true
Get strongly typed content
With your models defined and added to your application, you can use them when retrieving items from Kontent.ai.
// Tip: Find more about .NET SDKs at https://kontent.ai/learn/net
using Kontent.Ai.Delivery;
using KontentAiModels;
// Tip: Use DI to create Delivery client https://kontent.ai/learn/net-register-client
IDeliveryClient client = DeliveryClientBuilder
.WithEnvironmentId("8d20758c-d74c-4f59-ae04-ee928c0816b7")
.Build();
// Gets a content item by codename and maps it to the item's strongly typed model
IDeliveryItemResponse<Homepage> response = await client.GetItemAsync<Homepage>("hello_caas_world");
var homepage = response.Item;
// Use homepage
// Console.WriteLine(homepage.Headline);