ASP.NET Core中的ResponseType

问题描述 投票:2回答:1

我刚把我的项目从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中工作,返回结果在两个解决方案中也是相同的。

但是当查看来自客户端服务器的响应时,它们会有所不同。

enter image description here

因此,彼此之间唯一不同的是[ResponseType(typeof(HttpResponseMessage))]。在asp.net核心中有相同的东西吗?

c# asp.net asp.net-mvc asp.net-core
1个回答
1
投票

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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.