从ASP.NET 5 Web API返回文件

Joo*_*üüa 10 c# asp.net-web-api asp.net-core

我之前的问题:如何从ASP.net 5 web api返回文件

我试图返回一个文件作为Web API POST请求的响应.

我正在使用dnx451框架和rc1-final构建.控制器方法:

[HttpPost("")]
public ActionResult Post([FromBody]DocumentViewModel vm)
{
    try
    {
        if (ModelState.IsValid)
        {

            var Document = _repository.GetDocumentByGuid(vm.DocumentGuid, User.Identity.Name);
            var Params = Helper.ClientInputToRealValues(vm.Parameters, Document.DataFields);
            var file = Helper.GeneratePdf(Helper.InsertValues(Params, Document.Content));
            FileStream stream = new FileStream(file,FileMode.Open);

            return File(stream, "application/pdf", "test.pdf");

        }

    }
    catch (Exception ex)
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return null;
    }
    Response.StatusCode = (int)HttpStatusCode.BadRequest;
    return null;

}
Run Code Online (Sandbox Code Playgroud)

结果我得到一个名为"response"的文件.将其保存为pdf后,我尝试打开它,它说它已损坏.希望您能够帮助我.我使用Postman作为测试客户端.

谢谢

Ian*_*uty 20

请在另一篇文章中查看我的答案:返回文件作为回复

作为参考,我认为这符合您的需求:

public FileResult TestDownload()
{
    HttpContext.Response.ContentType = "application/pdf";
    FileContentResult result = new FileContentResult(System.IO.File.ReadAllBytes("YOUR PATH TO PDF"), "application/pdf")
    {
        FileDownloadName = "test.pdf"
    };

    return result;                                
}
Run Code Online (Sandbox Code Playgroud)

  • FileResult 和 FileContentResult 是 Mvc 类,不是 Webapi (2认同)

Mar*_*dle 11

我刚遇到这个问题并找到了解决方案.只要你有一个文件的绝对路径,那么你可以返回一个PhysicalFileResult并明确设置Content-Disposition标题Response,如下所示:

[HttpGet("{key}")]
public IActionResult Get(string key)
{
    var file = _files.GetPath(key);

    var result = PhysicalFile(file.Path, "text/text");

    Response.Headers["Content-Disposition"] = new ContentDispositionHeaderValue("attachment")
    {
        FileName = file.Name
    }.ToString();

    return result;
}
Run Code Online (Sandbox Code Playgroud)

使用PhysicalFile还具有以下优点:所有字节的异步流等都由框架来处理.