1

I am trying to download excel file from mvc method.

public ActionResult Download(string fileGuid, string fileName)
{   
        byte[] data = TempData[fileGuid] as byte[];
        return File(data, "application/vnd.ms-excel", fileName);

}

Getting error saying Non invocable member File cannot be used like a method. Which namespace do i need to use in order to get File method here in the above method.

  • 3
    It's not a matter of namespaces, it's a matter of having that method defined on a base class that your controller inherits from. You're probably looking for [this one](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase.file?view=aspnetcore-7.0#microsoft-aspnetcore-mvc-controllerbase-file(system-byte()-system-string-system-string)) – Damien_The_Unbeliever Feb 28 '23 at 07:59
  • 1
    You can only call `File()` in a controller. A controller is a class that inherits from `Controller` or `ControllerBase` – Panagiotis Kanavos Feb 28 '23 at 08:33
  • 1
    BTW why are you using the obsolete `xls` content type? This was replaced by `xlsx` 16 years ago. If you want to generate real Excel files in ASP.NET MVC you'll find answers that show just that, including [one I wrote](https://stackoverflow.com/a/32838151/134204). You can use libraries like EPPlus, ClosedXML, NPOI and more, to generate real Excel files, not HTML or CSV with fake extensions – Panagiotis Kanavos Feb 28 '23 at 08:35

1 Answers1

2

Like Damien_The_unbeliever has commented, you have to make sure the controller inherits the right base class which implements File as a method. This would in your case be ControllerBase.

public class DownloadController : ControllerBase
{
    public ActionResult Download(string fileGuid, string fileName)
    {   
        byte[] data = TempData[fileGuid] as byte[];
        return File(data, "application/vnd.ms-excel", fileName);
    }
}

This should allow you to use the File method

Roe
  • 633
  • 2
  • 14
  • Its working now after inheriting ControllerBase. Thanks for the help! – Abhishek Singh Feb 28 '23 at 09:59
  • @AbhishekSingh glad to hear that, don't forget to mark the answer as accepted. This will help others know that the question has been answered – Roe Feb 28 '23 at 10:00