ASP.NET Core 中的响应类型

Pre*_*cho 5 c# asp.net asp.net-mvc asp.net-core

我刚刚将项目从 ASP.Net 4.5 迁移到 ASP.Net Core。我有一个 REST API get,过去用于返回 blob,但现在返回 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)
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

ASP.net Core 中的代码除了[ResponseType(typeof(HttpResponseMessage))]在 ASP.Net Core 中不起作用之外是相同的,并且两种解决方案的返回结果也相同。

但是当在客户端查看服务器的响应时,它们是不同的。

在此输入图像描述

因此,它们之间唯一的区别是[ResponseType(typeof(HttpResponseMessage))]. ASP.NET Core 中有类似的东西吗?

Ven*_*ndi 7

Dot Net Core[ResponseType(typeof(HttpResponseMessage))] 相当于[Produces(typeof(HttpResponseMessage))]


Pre*_*cho 1

如何使用Web API Get方法返回图像

我通过改变我的回报解决了这个问题:

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • *不要*通过访问“Result”来阻止异步方法。这是使应用程序陷入僵局的绝佳方法。始终使用“await”,如果这是您的目标,则可以内联执行该操作,即“return File(await result.Content.ReadAsByteArrayAsync()...”。 (6认同)