0

I'm working a Controller that will generate/retrieve files. These will optionally set headers.

   public IActionResult SampleFileReport()
    {

I see the return type is IActionResult (a data contract). I see inside the function I can still set response.ContentType

Is there a preferred pattern for how to set ContentType in a controller?

I'm thinking it should be part of the DataContract and setting response.contentype is an anti-pattern, however I see examples such as this that utilize it. Returning a file to View/Download in ASP.NET MVC

ffejrekaburb
  • 656
  • 1
  • 10
  • 35

2 Answers2

2

All you need to do is return File:

public IActionResult SampleFileReport()
{
    // do stuff

    return File(bytes, mimetype, filename);
}

File also has overloads that accept Stream and string (path and filename to a file on the filesystem) in addition to byte[]. The mimetype is your content type, e.g. application/pdf, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet (Excel), etc. The final filename param is optional. If it's provided, a Content-Disposition: attachment header is sent with the response, which prompts the browser to pop a download dialog. Otherwise, the default Content-Disposition: inline is used, and the browser will try to load the returned file directly the browser tab/window, assuming the mime-type is supported for native rendering the browser. If not, then you'll get a download dialog, regardless.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
0

If we are talking about MVC (not .NET Core) then you can change IActionResult to FileContentResult

public FileContentResult SampleFileReport() 
{

    byte[] fileBytes = GetFileBytes();
    return File(fileBytes, MediaTypeNames.Application.Octet, "fileName");
}

Just checked this class still exists. FileContentResult .NET Core

SouXin
  • 1,565
  • 11
  • 17
  • thank you, I had tagged as .net core (but also mvc not sure if they're mutually exclusive) I am using .net core. Why did Microsoft take it out then? – ffejrekaburb Mar 21 '19 at 17:56
  • They didn't. `IActionResult` is an abstraction. There's no need to ever specify a specific action return type, even in ASP.NET MVC, but definitely not in ASP.NET Core. – Chris Pratt Mar 21 '19 at 18:06