htmlasp.net-mvcactionresultcontroller-action

How to serve html file from another directory as ActionResult


I have a specialised case where I wish to serve a straight html file from a Controller Action.

I want to serve it from a different folder other than the Views folder. The file is located in

Solution\Html\index.htm

And I want to serve it from a standard controller action. Could i use return File? And how do I do this?


Solution

  • If you want to render this index.htm file in the browser then you could create controller action like this:

    public void GetHtml()
    {
        var encoding = new System.Text.UTF8Encoding();
        var htm = System.IO.File.ReadAllText(Server.MapPath("/Solution/Html/") + "index.htm", encoding);
        byte[] data = encoding.GetBytes(htm);
        Response.OutputStream.Write(data, 0, data.Length);
        Response.OutputStream.Flush();
    }
    

    or just by:

    public ActionResult GetHtml()
    {
        return File(Server.MapPath("/Solution/Html/") + "index.htm", "text/html"); 
    }
    

    So lets say this action is in Home controller and some user hits http://yoursite.com/Home/GetHtml then index.htm will be rendered.

    EDIT: 2 other methods

    If you want to see raw html of index.htm in the browser:

    public ActionResult GetHtml()
    {
        Response.AddHeader("Content-Disposition", new System.Net.Mime.ContentDisposition { Inline = true, FileName = "index.htm"}.ToString());
        return File(Server.MapPath("/Solution/Html/") + "index.htm", "text/plain"); 
    }
    

    If you just want to download file:

    public FilePathResult GetHtml()
    {
        return File(Server.MapPath("/Solution/Html/") + "index.htm", "text/html", "index.htm"); 
    }