我正在开发一个小项目,该项目使用在WPF应用程序中托管的Nancy。我希望能够远程下载大约8MB的PDF文件。我能够让下载工作,但在下载过程中,应用程序将不会响应任何其他请求。有没有办法允许文件下载而不会占用所有其他请求?
Public Class ManualsModule : Inherits NancyModule
Public Sub New()
MyBase.New("/Manuals")
Me.Get("/") = Function(p)
Dim model As New List(Of String) From {"electrical", "opmaint", "parts"}
Return View("Manuals", model)
End Function
Me.Get("/{name}") = Function(p)
Dim manualName = p.name
Dim fileResponse As New GenericFileResponse(String.Format("Content\Manuals\{0}.pdf", manualName))
Return fileResponse
End Function
End Sub
End Class
或者在C#中
public class ManualsModule : NancyModule
{
public ManualsModule() : base("/Manuals")
{
this.Get("/") = p =>
{
List<string> model = new List<string> {
"electrical",
"opmaint",
"parts"
};
return View("Manuals", model);
};
this.Get("/{name}") = p =>
{
dynamic manualName = p.name;
GenericFileResponse fileResponse = new GenericFileResponse(string.Format("Content\\Manuals\\{0}.pdf", manualName));
return fileResponse;
};
}
}
答案 0 :(得分:11)
var file = new FileStream(zipPath, FileMode.Open);
string fileName = //set a filename
var response = new StreamResponse(() => file, MimeTypes.GetMimeType(fileName));
return response.AsAttachment(fileName);
答案 1 :(得分:4)
最简单的方法是围绕它创建一个StreamWriter,如下所示:
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;
答案 2 :(得分:3)
我发现我实际上是在WCF中托管Nancy而不是自托管主机。我描述的行为仅在WCF中托管时发生。自我主机将适用于我的应用程序,所以我会继续。
答案 3 :(得分:0)
如果您希望将文件作为附件,Monivs的答案很有用,如果您想直接在浏览器中打开pdf,可以这样做:
MemoryStream ms = new MemoryStream(documentBody);
var response = new Response();
response.ContentType = "application/pdf";
response.Contents = stream => {
ms.WriteTo(stream);
};
return response;