在asp.net 5中创建了wep api。我想回复Post请求的文件响应。但不是文件,响应看起来像 `
{
"version": {
"major": 1,
"minor": 1,
"build": -1,
"revision": -1,
"majorRevision": -1,
"minorRevision": -1
},
"content": {
"headers": [
{
"key": "Content-Disposition",
"value": [
"attachment; filename=test.pdf"
]
},
{
"key": "Content-Type",
"value": [
"application/pdf"
]
}
]
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [],
"requestMessage": null,
"isSuccessStatusCode": true
}`
代码:
public HttpResponseMessage 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));
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(System.IO.File.ReadAllBytes(file))
};
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "test.pdf"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return result;
}
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return null;
}
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return null;
}
如何将真实文件作为响应而不是JSON返回?我使用Postman作为测试客户端。
答案 0 :(得分:5)
使用IActionResult而不是HttpResponseMessage。并返回FileStreamResult,并使其工作。
遇到新问题,该文件不是我用来自服务器的流打开的文件。但是会为此创造一个新问题。
继续:Return file from ASP.NET 5 Web API
由于
答案 1 :(得分:1)
试试这个!
example.com
答案 2 :(得分:0)
设置HttpContext.Response.ContentType = "application/pdf"
是否有帮助?
这应该符合您的需求:
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;
}