As explained in ASP.NET Core, HTTPRequestMessage returns a strange JSON message , ASP.NET Core does not support returning HttpResponseMessage
(which package did you install to access this type?).
Because of this, the serializer simply writes all the output properties of the HttpResponseMessage
to the output, as it would with any other unsupported response type.
To support custom responses, you must return IActionResult
-implementing. There are many of them . In your case, I would look in FileStreamResult
:
public IActionResult Get(int id) { var stream = new FileStream(@"path\to\file", FileMode.Open); return new FileStreamResult(stream, "application/pdf"); }
Or just use PhysicalFileResult
, where the stream is processed for you:
public IActionResult Get(int id) { return new PhysicalFileResult(@"path\to\file", "application/pdf"); }
Of course, all this can be simplified by using helper methods such as Controller.File()
:
public IActionResult Get(int id) { var stream = new FileStream(@"path\to\file", FileMode.Open); return File(stream, "application/pdf", "FileDownloadName.ext"); }
This simply abstracts the creation of a FileContentResult
or FileStreamResult
(the latter for this overload).
Or, if you are converting an old MVC application or web API and donβt want to convert all your code at once, add a link to WebApiCompatShim (NuGet) and wrap your current code in a ResponseMessageResult
:
public IActionResult Get(int id) { var response = new HttpResponseMessage(HttpStatusCode.OK); var stream = ... response.Content... return new ResponseMessageResult(response); }
If you do not want to use return File(fileName, contentType, fileDownloadName)
, then FileStreamResult
does not support setting the content-disposition header from the constructor or through properties.
In this case, you will have to add the response header to the answer yourself before returning the result of the file:
var contentDisposition = new ContentDispositionHeaderValue("attachment"); contentDisposition.SetHttpFileName("foo.txt"); Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();