ASP.NET MVC:返回纯文本文件以从控制器方法下载 [英] ASP.NET MVC: returning plaintext file to download from controller method

查看:14
本文介绍了ASP.NET MVC:返回纯文本文件以从控制器方法下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Consider the need to return a plain-text file from a controller method back to the caller. The idea is to have the file downloaded, rather than viewed as plaintext in the browser.

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

I have the following method, and it works as expected. The file is presented to the browser for download, and the file is populated with the string.

我想寻找这个方法的更正确"的实现,因为我对 void 返回类型不是 100% 满意.

I'd like to look for a 'more correct' implementation of this method, as I am not 100% comfortable with the void return type.

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();
}

推荐答案

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

Use the File method on the controller class to return a FileResult

public ActionResult ViewHL7( int id )
{
    ...

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

这篇关于ASP.NET MVC:返回纯文本文件以从控制器方法下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆