ASP.NET MVC > Output

Returning file content from action method in ASP.NET MVC

How to output a file content from controller action method?


To output a file content from the controller action method, we use FileResult as return type of the action method. .

CONTROLLER CODE

public FileResult OutputFile()
  {
      string path = Server.MapPath("~/Views/Home/About.cshtml");
      return File(path, "text/html");
      // return File(path, "text/html", "MyFile.txt");
  }

In the above code, we are getting the path of the file to return. Now we are using File method that accepts file path and content type to return the file content to the browser..

If we pass third parameter called “fileDownloadName”, it forces the user to download the file instead of rendering its content in the browser.

POINT OF INTEREST

Play with different overload methods of the returning File method, it also accepts byte array or Stream in case we do not want any physical file to send as result and build the file content on the fly.

 Views: 4023 | Post Order: 66



Write for us