RickStrahl/Westwind.AspNetCore.Markdown

Null Exception in MarkdownPageProcessorController.ParseMarkdownToModel

taarskog opened this issue · 0 comments

Hi Rick,

Found what I suspect is a small bug in the current code. Can be reproduced by running SampleWeb30 and going to http://localhost:59805/docs/.

image

The following fix seems to do the trick:

        private MarkdownModel ParseMarkdownToModel(string markdown, MarkdownModel model = null)
        {
            if (model == null)
                model = new MarkdownModel();

            string yaml = null;
            string firstLinesText = null;
/*BAD*/ List<string> firstLines = null; // <=== Causes null-exception if no "---" at start of markdown
/*WORKS*/ List<string> firstLines = StringUtils.GetLines(markdown, 50).ToList();
            
            if (markdown.StartsWith("---"))
            {
/* REMOVE*/                firstLines = StringUtils.GetLines(markdown, 50).ToList();
                firstLinesText = String.Join("\n", firstLines);
                yaml = StringUtils.ExtractString(firstLinesText, "---", "---", returnDelimiters: true);
            }

            if (yaml != null && yaml.Contains("basePath: "))
                model.BasePath = StringUtils.ExtractString(yaml, "basePath: ", "\n")?.Trim();
            if (string.IsNullOrEmpty(model.BasePath))
                model.BasePath = model.FolderConfiguration.BasePath;

            if (model.FolderConfiguration.ExtractTitle )
            {

                if (yaml != null)
                {
                    model.Title = StringUtils.ExtractString(yaml, "title: ", "\n");
                    model.YamlHeader = yaml.Replace("---", "").Trim();
                }

                // if we don't have Yaml headers the header has to be closer to the top
/*SEE HERE*/                firstLines = firstLines.Take(10).ToList(); // <=== EXCEPTION WITH CURRENT CODE!

Small change so probably quickest/easiest for you to fix, but let me know if you want a PR.

-Trond