Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 337
Aran Mulholland Avatar asked May 31 '12 08:05

Aran Mulholland


People also ask

What is the ActionResult ()?

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.

How do I return HTML Web API?

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.

What is ActionResult return type?

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.


2 Answers

Check this out :

    public ActionResult Index()     {         return new FilePathResult("~/Html/index.htm", "text/html");     } 
like image 91
Wahid Bitar Avatar answered Sep 19 '22 09:09

Wahid Bitar


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");  } 
like image 44
lucask Avatar answered Sep 23 '22 09:09

lucask