从ASP.NET的Web 5 API返回的文件 [英] Return file from ASP.NET 5 Web API
问题描述
我的previous问题:<一href=\"http://stackoverflow.com/questions/34853072/how-to-return-file-from-asp-net-5-web-api/34856354#34856354\">How从ASP.net 5网页API返回文件
My previous question: How to return file from ASP.net 5 web api
我试图返回一个文件从网页API POST请求的响应。
I am trying to return a file as the response from Web API POST request.
我使用dnx451框架和RC1-最终版本。控制方法:
I'm using dnx451 framework and rc1-final build. Controller method:
[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;
}
至于结果我得到一个名为回应的文件。将其保存为PDF格式后,我尝试打开它,它说,它已损坏。希望你能帮助我。我使用的邮差作为测试客户端。
As result I get a file with name "response". After saving it as pdf i try to open it, and it says it is damaged. Hope you can help me. I am using Postman as test client.
感谢
推荐答案
请参阅其他职位我的回答:返回文件作为响应
Please see my answer in the other post: Return file as response
有关参考,我觉得这适合您的需要:
For reference, I think this fits your needs:
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;
}
这篇关于从ASP.NET的Web 5 API返回的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!