我之前的问题:How to return file from ASP.net 5 web api
我正在尝试返回一个文件作为 Web API POST 请求的响应。
我正在使用 dnx451 框架和 rc1-final 构建。 Controller 方法:
[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;
}
结果我得到一个名为“response”的文件。将其保存为 pdf 后,我尝试打开它,它说它已损坏。希望您能够帮助我。我正在使用 Postman 作为测试客户端。
谢谢
最佳答案
请参阅我在另一篇文章中的回答:Return file as response
作为引用,我认为这符合您的需求:
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;
}
关于c# - 从 ASP.NET 5 Web API 返回文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34856983/