Ara*_*and 36 html asp.net-mvc actionresult controller-action
我有一个专门的案例,我希望从Controller Action提供一个直接的html文件.
我想从Views文件夹以外的其他文件夹中提供它.该文件位于
Solution\Html\index.htm
Run Code Online (Sandbox Code Playgroud)
我想从标准的控制器动作中提供服务.我可以使用返回文件吗?我该怎么做?
Wah*_*tar 47
看一下这个 :
public ActionResult Index()
{
return new FilePathResult("~/Html/index.htm", "text/html");
}
Run Code Online (Sandbox Code Playgroud)
luc*_*ask 41
如果要在浏览器中呈现此index.htm文件,则可以创建如下控制器操作:
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();
}
Run Code Online (Sandbox Code Playgroud)
或者只是:
public ActionResult GetHtml()
{
return File(Server.MapPath("/Solution/Html/") + "index.htm", "text/html");
}
Run Code Online (Sandbox Code Playgroud)
因此,假设此操作位于Home控制器中,并且某些用户点击http://yoursite.com/Home/GetHtml,则会呈现index.htm.
编辑:2其他方法
如果你想在浏览器中看到index.htm的原始html :
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");
}
Run Code Online (Sandbox Code Playgroud)
如果您只想下载文件:
public FilePathResult GetHtml()
{
return File(Server.MapPath("/Solution/Html/") + "index.htm", "text/html", "index.htm");
}
Run Code Online (Sandbox Code Playgroud)
我扩展了wahid的答案来创建HtmlResult
创建扩展FilePathResult的Html结果
public class HtmlResult : FilePathResult
{
public HtmlResult(string path)
: base(path, "text/html")
{
}
}
Run Code Online (Sandbox Code Playgroud)
在控制器上创建静态方法
public static HtmlResult Html(this Controller controller, string path)
{
return new HtmlResult(path);
}
Run Code Online (Sandbox Code Playgroud)
像我们返回视图一样使用
public HtmlResult Index()
{
return this.Html("~/Index.html");
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你
| 归档时间: |
|
| 查看次数: |
39665 次 |
| 最近记录: |