[RESOLVED]How to easily serve up just HTML content on MVC site.

I have a link in a cshtml view that points to static HTML content showing configuration changes I made to _Layout.cshtml….  (I want to show others what changes they have to make to do this thing I want to show)….  The link in the view (CSHMTL) file is

<a href="~/Views/Shared/_Layout.html">Changes to Layout</a>

As you can see I put it in the same folder where _Layout.cshtml file is located, but clicking on that link above returns 404.  

What’s best way ( I don’t care if it’s in the Shared folder or not) to serve up just static HTML content?

Ok here’s the solution:

Step 1) Remember that MVC is wired up for segmented path routing, it does not like file name extensions in the inbound route request.  

It will not out-of-the-box serve up .html files referenced like this: 

<a href="~/Views/Shared/_Layout.html">Changes to Layout</a>

Step 2) First create an action method that will take in a string like this:

        public ActionResult GetHTMLFile(string filename)
            var dir = "/Views/HTML/";
            var suffix = ".html";
            var path = dir + filename + suffix;
            return new FilePathResult(path, "text/html");

Note that we are building the path statement inside of the method. We have a folder named HTML in the Views folder and we are going to append the suffix .html as all the files there end with html.  We are using the FilePathResult method to read the file
and setting the context to "text/html".

Step 3) Might as well use the HTMLHelper ActionLink method rather than coding it up manually because it allows you to configure the actionmethod name. 

@Html.ActionLink("Layout File changes", "GetHTMLFile", new {filename="_Layout"}) 

In the Action link,  we set the title of the link and in this case the action method name as shown above.  We didn’t have to specify the controller  name because we only have one controller in our solution.  Finally, to get the string into the controller
parameter, we created an anonymous object to tell it what file name we wanted to serve!  

And that’s it!

BTW, there’s a post out there by Jon Galloway showing how to tweak the WebConfig file to alter IIS behavior, it doesn’t work in my situation.


We are happy that your issue has been resolved. And thanks for sharing solution with us.

Leave a Reply