Skip to content

Instantly share code, notes, and snippets.

@joeriks
Created September 13, 2012 12:46
Show Gist options
  • Save joeriks/3714093 to your computer and use it in GitHub Desktop.
Save joeriks/3714093 to your computer and use it in GitHub Desktop.
Use webapi to download file as attachment (using AttributeRouting)
[RoutePrefix("files")]
public class FilesController : ApiController
{
[GET("somepdf/{id}")]
public HttpResponseMessage GetSomePdf(string id)
{
var path = MyApp.PathToSomePdf(id);
if (path!= null)
return FileAsAttachment(path, "somepdf.pdf");
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
public static HttpResponseMessage FileAsAttachment(string path, string filename)
{
if (File.Exists(path))
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = filename;
return result;
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
@dskc
Copy link

dskc commented Oct 24, 2017

"result" is returning "StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Content-Type: application/octet-stream Content-Disposition: attachment; filename=asdfwer.pdf }" as response.write kind..

What could have been gone wrong?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment