问题描述
我有,我想从一个控制器动作发球直html文件,一个专门的案件。
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
和我想从一个标准的控制器操作为它服务。我能使用return文件?和
我该怎么做呢?
And I want to serve it from a standard controller action. Could i use return File? Andhow do I do this?
推荐答案
如果要呈现在浏览器这个index.htm文件,那么你可以创建这样的控制器操作:
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();
}
或者只是:
public ActionResult GetHtml()
{
return File(Server.MapPath("/Solution/Html/") + "index.htm", "text/html");
}
因此,可以说这次行动是的首页的控制器和一些用户点击的index.htm的将被渲染。
So lets say this action is in Home controller and some user hits http://yoursite.com/Home/GetHtml then index.htm will be rendered.
编辑:2其他方法
如果你想看到的原始HTML的的index.htm 的浏览器:
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");
}
这篇关于如何从另一个目录服务的ActionResult HTML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!