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

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

问题描述

考虑需要从控制器方法返回给调用者返回一个纯文本文件。我们的想法是具有文件下载,而不是作为在浏览器中的明文观看。

我有以下的方法,它按预期工作。该文件是psented到浏览器下载$ P $,并且该文件中填充该字符串。

我想看看这个方法的比较正确的实现,因为我不舒服的无效返回类型。

100%

 公共无效ViewHL7(INT ID)
{
    字符串someLongTextForDownload =ABC123    Response.Clear();
    Response.ContentType =text / plain的;
    Response.AddHeader(内容处置的String.Format(附件;文件名= {0} .hl7,id.ToString()));
    的Response.Write(someLongTextForDownload);
    到Response.End();
}


解决方案

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

 公众的ActionResult ViewHL7(INT ID)
{
    ...    返回文件(Encoding.UTF8.GetBytes(someLongTextForDownLoad)
                 text / plain的,
                  的String.Format({0} .hl7,ID));
}

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.

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

解决方案

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天全站免登陆