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):

This article provided some great insight on how to accomplish this:

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

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