Thursday, November 19, 2015

Downloading a file from an ASP.NET MVC View

If you want to allow a user to download a file from your ASP.NET MVC View, then you will need to return a FileStreamResult (or any of the derived classes from FileResult): https://msdn.microsoft.com/en-US/library/system.web.mvc.fileresult%28v=vs.118%29.aspx

This article provided some great insight on how to accomplish this: https://gist.github.com/johnmmoss/8ee16837513ab69de4f3

Since I needed to render an RDF file to the browser, this was the code that I ultimately ended up using:

[HttpGet]
public FileStreamResult DownloadTurtleFile()
{
 
    string rdfContent = GetRDFContent();
 
    byte[] fileContent = Encoding.Unicode.GetBytes(rdfContent);
    var stream = new MemoryStream(fileContent);
    var fileStreamResult = new FileStreamResult(stream, "application/x-turtle");
    fileStreamResult.FileDownloadName = "RDFFile.ttl";
    return fileStreamResult;
}

No comments:

Post a Comment