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?
An action result is what a controller action returns in response to a browser request. The ASP.NET MVC framework supports several types of action results including: ViewResult - Represents HTML and markup.
The first string represents the content of the HTML while the last is the content-type which for HTML is "text/html" . Since our controller derives from ControllerBase , we simply call base. Content() and pass the required parameter to return the desired HTML.
An ActionResult is a return type of a controller method in MVC. Action methods help us to return models to views, file streams, and also redirect to another controller's Action method.
Check this out :
public ActionResult Index() { return new FilePathResult("~/Html/index.htm", "text/html"); }
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"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With