tags:

views:

22

answers:

1

I want to craft a Response and add file attachment headers, is this the way to go about doing this in ASP.NET MVC Action? Normally I return things like int, string, or more commonly ActionResult. But can I return an HttpResponse directly back to their browser like this?

So if they go to /controller/action/ it would return that HTTP response to their browser.

+2  A: 

I use the FilePathResult return type whenever I want to return a file for download to the user:

public FilePathResult DownloadFile() {
    FilePathResult file = new FilePathResult("c:\\test.txt", "text/plain");
    return file;
}

The first param is the path to the file on your local system (or network share), the second param is the mime-type you want reported to the browser. You can set file.FileDownloadName if you want to manually customize the file name the user will see when prompted to download it.

Edit: Found a decent overview of the different options (FilePathResult, FileStreamResult, FileContentResult) incase you want to read up on it a bit more (bottom third of the post).

Parrots
cool, do you know with this method if I return say an .mp3 will it get played by the browser or will it be downloaded? I know if I send them directly to the mp3 file with a redirect it will be played by most browsers and I want to force download
shogun
I think it sets the HTTPHeader 'Content-Disposition' to 'attachment', which is what will force that to happen. Not 100% sure at the moment though. Worst case grab a hold of the HTTPResponse before you return the file and make sure that header is set.
Parrots
+1 @Ryan if the FilePathResult or the others don't work as you want it to, you can create your own custom result for it / which would be pretty much the code you intend to write (do some stuff in the respond object).
eglasius
hmm what if the file path is a URI pointing to the file on another server?
shogun
As long as the current server has access to it somehow (samba usually) then you're fine. I've used it with accessing a share on another computer without issue.
Parrots