Reputation: 1920
I just moved my project to ASP.Net Core from ASP.Net 4.5. I've a REST API get that used to return a blob but now is returning JSON instead.
This is the old code:
[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)
};
}
}
The code in ASP.net Core is the same except for [ResponseType(typeof(HttpResponseMessage))]
not working in ASP.Net Core, also the return result is also the same in both solutions.
But when looking at the response from the server in the client they differ.
So the only thing that differs them both from each other are the [ResponseType(typeof(HttpResponseMessage))]
. Is there something equivalent in asp.net core?
Upvotes: 5
Views: 14159
Reputation: 23
Edit: @President Camacho said that [ResponseType...] would not work in .net core. It has been replaced by [ProducesResponseType]:
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(List<int>))]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<IEnumerable<User>>> Get...()
The explanation from Microsoft is fine: https://learn.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-6.0#iactionresult-type A quote from the website sums it up: "This attribute produces more descriptive response details for web API help pages generated by tools like Swagger."
And it's good for other team members who don't want to look at the source code to develop the UI.
Upvotes: 0
Reputation: 5640
Dot Net Core equivalent to [ResponseType(typeof(HttpResponseMessage))]
is [Produces(typeof(HttpResponseMessage))]
Upvotes: 8
Reputation: 1920
How to to return an image with Web API Get method
I solved it by changing my return:
[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);
}
}
Upvotes: 1