我刚把我的项目从ASP.Net 4.5移到ASP.Net Core。我有一个用于返回blob的REST API get,但现在返回JSON。
这是旧代码:
[HttpGet]
[ResponseType(typeof(HttpResponseMessage))]
[Route("Download/{documentId}")]
public async Task<HttpResponseMessage> DownloadDocument(string documentId)
{
try
{
var result = await TheDocumentService.DownloadDocument(documentId);
return result;
}
catch (Exception ex)
{
return new HttpResponseMessage
{
StatusCode = HttpStatusCode.InternalServerError,
Content = new StringContent(ex.Message)
};
}
}
ASP.net Core中的代码是相同的,除了[ResponseType(typeof(HttpResponseMessage))]
不能在ASP.Net Core中工作,返回结果在两个解决方案中也是相同的。
但是当查看来自客户端服务器的响应时,它们会有所不同。
因此,彼此之间唯一不同的是[ResponseType(typeof(HttpResponseMessage))]
。在asp.net核心中有相同的东西吗?
How to to return an image with Web API Get method
我通过改变我的回报来解决它:
[HttpGet]
[Route("Download/{documentId}")]
public async Task<IActionResult> DownloadDocument(string documentId)
{
try
{
var result = await TheDocumentService.DownloadDocument(documentId);
var content = await result.Content.ReadAsByteArrayAsync();
return File(content, result.Content.Headers.ContentType.ToString());
}
catch (Exception ex)
{
return StatusCode(500, ex);
}
}