I use the following two prototype structs in Entry Model Classes (https://deliverystack.net/2020/07/20/net-core-headless-cms-entry-models-and-entry-model-classes/) to represent Field Values from Entries where those values may contain markup or markdown. These classes use HtmlString properties to expose values without the need for method calls such as @Html.Raw() to prevent ASP.NET MVC from encoding HTML that should not be encoded.
I use struct because Michael Davis (https://www.linkedin.com/in/michael-evan-davis/) suggested that these feel like value types. I rarely use struct and wanted to explore their capabilities and implementation a bit. My understanding is that ASP.NET may allocate value types on the stack, which increases efficiency, but may not be appropriate when accessing cached data from multiple threads? Maybe I can find a way to ensure that stucts get allocated on the heap (is the compiler, the runtime, or something else responsible for that, and how does it decide?) So if I found these structs in the stack (where I have never actually looked), or just to experiment, I might change struct to object and evaluate any performance impact, or find some other way to ensure their allocation on the heap (preferably as structs, I think). Update: https://stackoverflow.com/questions/4853213/are-structs-always-stack-allocated-or-sometimes-heap-allocated “you really don’t need to concern yourself with this stuff. You should be concerned with the semantic difference between value types and reference types”
The struct for markup turned out to be less useful than I had expected because Contentful uses a proprietary JSON format to represent markup (https://deliverystack.net/2020/07/22/some-of-the-reasons-why-i-do-not-like-how-contentful-represents-rich-text-fields/). This class demonstrates using HtmlAgilityPack (https://html-agility-pack.net/) to add target attributes to anchors that do not start with a slash, which should indicate a different website or alternate protocol.
I haven’t tried the Contentful Markdown implementation (https://www.contentful.com/blog/2020/05/25/beginners-guide-to-contentful-text-types-markdown-richtext/); only the JSON format. This implementation for markdown uses Markdig (https://github.com/lunet-io/markdig), the same markdown library used by the Contentstack SDK (along with Newtonsoft.Json), but does not have a dependency on Contentstack.
These classes belong in a project that does not depend on any CMS vendor, which other .NET solutions can use to access the CMS.
2 thoughts on “Entry Model structs for Markup Fields”