File downloads in a self-host Nancy application

半世苍凉 提交于 2019-12-04 05:16:01
var file = new FileStream(zipPath, FileMode.Open);
string fileName = //set a filename

var response = new StreamResponse(() => file, MimeTypes.GetMimeType(fileName));
return response.AsAttachment(fileName);

The easiest way is to create a StreamWriter around it, like this:

var response = new Response();

response.Headers.Add("Content-Disposition", "attachment; filename=test.txt");
response.ContentType = "text/plain";
response.Contents = stream => {
    using (var writer = new StreamWriter(stream))
    {
        writer.Write("Hello");
    }
};

return response;

I found that I was actually hosting Nancy in WCF not self-host. The behaviour I described only happens when hosted in WCF. Self-Host will work fine for my application so I'll go with that.

Monivs answer works great if you want the file as a attachement, if you want to open the pdf directly in the browser you can do it like this:

MemoryStream ms = new MemoryStream(documentBody);
var response = new Response();
response.ContentType = "application/pdf";
response.Contents = stream => {
    ms.WriteTo(stream);
};
return response;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!