【问题标题】:ASP.NET MVC: returning plaintext file to download from controller methodASP.NET MVC:返回纯文本文件以从控制器方法下载
【发布时间】:2009-10-14 23:18:07
【问题描述】:

考虑需要将纯文本文件从控制器方法返回给调用者。这个想法是下载文件,而不是在浏览器中以纯文本形式查看。

我有以下方法,它按预期工作。该文件被呈现给浏览器以供下载,并且该文件用字符串填充。

我想寻找此方法的“更正确”实现,因为我对 void 返回类型不是 100% 满意。

public void ViewHL7(int id)
{
    string someLongTextForDownload = "ABC123";

    Response.Clear(); 
    Response.ContentType = "text/plain";
    Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.hl7", id.ToString()));
    Response.Write(someLongTextForDownload);
    Response.End();
}

【问题讨论】:

    标签: asp.net-mvc controller download


    【解决方案1】:

    使用控制器类的 File 方法返回一个 FileResult

    public ActionResult ViewHL7( int id )
    {
        ...
    
        return File( Encoding.UTF8.GetBytes( someLongTextForDownLoad ),
                     "text/plain",
                      string.Format( "{0}.hl7", id ) );
    }
    

    【讨论】:

    • Tks tvanfosson。你的回答对我帮助很大。
    • 如果 SO 可以拿起 .net 类,这样我们就可以看到重载而不用谷歌搜索,这不是很好吗:p
    【解决方案2】:

    您需要从您的方法中返回一个FileContentResult

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 2012-07-18
      • 2011-08-15
      • 2019-02-11
      相关资源
      最近更新 更多