2012-05-31 41 views
29

我有一個專門的案例,我希望從Controller Action提供一個直接的html文件。如何從另一個目錄提供html文件作爲ActionResult

我想從除了Views文件夾以外的其他文件夾提供它。該文件位於

Solution\Html\index.htm 

而我想從一個標準的控制器操作它。我可以使用返回文件嗎?和 我該如何做到這一點?

回答

33

如果要呈現在瀏覽器這個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(); 
} 

或只是:

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

因此,可以說這次行動是在首頁控制器和一些用戶點擊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"); 
} 

如果你只是想下載文件:

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

'Server.MapPath'不是必需的。只需嘗試'返回文件(「〜/ Html/index.htm」,「text/html」);' –

+1

你需要使用什麼庫來使用'File()'? –

0

你可以讀取字符串中的html文件並將其返回到行動中嗎? ?如下圖所示它呈現爲HTML網頁:

public string GetHtmlFile(string file) 
{ 
    file = Server.MapPath("~/" + file); 
    StreamReader streamReader = new StreamReader(file); 
    string text = streamReader.ReadToEnd(); 
    streamReader.Close(); 
    return text; 
} 

首頁/ GetHtmlFile文件=解決方案\ HTML \ index.htm的

如果HTML文件的目標文件或存儲機制很複雜,然後你可以在你Virtual path provider

Virtual path provider MVC sample

38

查看結果:

public ActionResult Index() 
    { 
     return new FilePathResult("~/Html/index.htm", "text/html"); 
    } 
+3

best anwer.Works perfect – om471987

+0

不客氣的朋友:) –

+1

'return File(「〜/ Html/index.htm」,「text/html」);'是最短的答案; D –

7

我伸出瓦希德的答案創建HtmlResult

創建延伸FilePathResult的Html結果

public class HtmlResult : FilePathResult 
{ 
    public HtmlResult(string path) 
     : base(path, "text/html") 
    { 
    } 
} 

使用就像我們在控制器

public static HtmlResult Html(this Controller controller, string path) 
{ 
    return new HtmlResult(path); 
} 

創建靜態方法返回查看

public HtmlResult Index() 
{ 
    return this.Html("~/Index.html"); 
} 

希望它有幫助

+0

可愛.........-> –

0

我想把我的兩美分。我發現這個最簡潔,它已經在那裏:

public ActionResult Index() 
{ 
    var encoding = new System.Text.UTF8Encoding(); 
    var html = ""; //get it from file, from blob or whatever 
    return this.Content(html, "text/html; charset=utf-8"); 
} 
相關問題