Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Return Markdown Directly From Your ASP.NET MVC Controller

0.00/5 (No votes)
22 Apr 2016 1  
Return markdown directly from your ASP.NET MVC controller

Want to return markdown directly from your ASP.NET MVC controller? Here is how you do it.

You can use my MarkdownWeb nuget package. It uses the MarkdownDeep package for the markdown parsing, but adds features such as github tables syntax and fenced code blocks.

To use it, simply create a new markdown file and add it to a view folder:

views folder

View Contents

# Hello world!

This is some tough sh*t.

## Table

Table demo

 Column 1 | Column 2 
----- | ------
Value 1 | Value A
Value 2 | Value B

Then call it from your controller:

C#
public ActionResult Info()
{
    return new MarkdownResult("info");
}

Result

markdown result

The magic is done thanks to my nuget package and the following action result:

public class MarkdownResult : ActionResult
{
    private readonly string _fileName;
    private readonly string _markdownFullPath;

    public MarkdownResult(string virtualPathOrMarkdownViewName)
    {
        if (virtualPathOrMarkdownViewName == null)
            throw new ArgumentNullException(nameof(virtualPathOrMarkdownViewName));
        if (virtualPathOrMarkdownViewName.StartsWith("~"))
            _markdownFullPath = HostingEnvironment.MapPath(virtualPathOrMarkdownViewName);
        else
            _fileName = virtualPathOrMarkdownViewName;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        string fullPath;
        if (_fileName != null)
        {
            var fullName = string.Format("~\\Views\\{0}\\{1}",
                context.Controller.GetType().Name.Replace("Controller", ""), _fileName);
            fullPath = HostingEnvironment.MapPath(fullName);
        }
        else
        {
            fullPath = _markdownFullPath;
        }
        if (!fullPath.EndsWith(".md", StringComparison.OrdinalIgnoreCase))
            fullPath += ".md";

        var path = Path.GetDirectoryName(fullPath);
        var repos = new FileBasedRepository(path);
        var parser = new PageService(repos, new UrlConverter("/"));
        var fileContents = File.ReadAllText(fullPath);
        var result = parser.ParseString("/", fileContents);
        context.HttpContext.Response.Write(result.Body);
    }
}

Enjoy!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here