Every development career has milestone moments. One we all likely share is building a custom content management system, or CMS, as developers like to refer to it. A common approach to melding metadata and content is utilizing the old reliable Markdown format, which fuses YAML frontmatter with a simple content format. While YAML is flexible, it can be less than ideal when wanting to use that embedded data in your ASP.NET Core applications.
In this post, I’ll show you a quick experiment around processing Markdown files and their YAML into a strongly-type C# object. The example allows you to easily modify content while still having access to instances of data that you can strongly type.
The Magnificent Markdown
Markdown is a very flexible format whose strength comes from its simplicity. Let’s examine a document that defines a person’s profile.
The top of the document defines a data model with properties for Name
, Profession
, and Hobbies
. The C# data model for this YAML would consist of three properties.
Let’s build an object that will parse the Markdown file’s front matter while helping us render the content into HTML for use on a Razor page.
The MarkdownObject and Parsing Files
For my experiment, I created a MarkdownObject<T>
class that takes a content string and parses the document into its parts. The T
argument is up to the developer to determine.
To continue with the code, you must add the Markdig
package and the YamlDotNet
package.
Let’s look at the implementation next.
In the case of this demo, we’ll create an instance of MarkdownObject<Asset>
. Let’s see how to use this type in a Razor Page.
MarkdownObject in a Razor Page
In my demo, I have all my Markdown files in a Data
directory. Each file in the data directory has a unique file name that we’ll use in our Razor Page as a slug
. We’ll also use the Model to output the data and the processed HTML into a structured layout.
So, what does the page’s model look like?
The OnGet
method contains some protective code to prevent access to other files, but it’s ultimately pretty straightforward. When you go to /profile/Khalid,
you’ll see a nicely formatted page that mixes data and content into predetermined HTML because we use the new MarkdownObject
class. Sweet!
I’ve pushed the code to my GitHub repository so you can try this sample for yourself. Please give it a try and let me know what you think. As always, thanks for reading and sharing my posts. Cheers.