2013-11-21 95 views
6

我正在研究一个使用Nancy在WPF应用程序中托管的小型项目。我希望能够远程下载大约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; 
     }; 
    } 
} 

回答

3

我发现,我其实是在WCF不能自主机托管南希。我描述的行为只发生在WCF中时。自主服务器对我的应用程序来说工作得很好,所以我会继续这样做。

+0

这个问题可能是周转基金围绕最大消息尺寸神秘的配置 - 但如果自我主机是为你工作,这是一个更好的选择,反正海事组织:) –

10
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

愚蠢的问题:因为你不能在return语句之前关闭流 - 在Nancy完成之后,流会自动关闭吗?我猜它确定.. – RhinoDevel

+1

**流应该由委托创建。**这可能是StreamResponse需要一个动作而不是流对象的原因:'new StreamResponse((=)=> new FileStream( zipPath,FileMode.Open),MimeTypes.GetMimeType(fileName));' – JanDotNet

2

最简单的方法是创建一个StreamWriter周围,像这样的:如果你想要的文件作为attachement

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; 
0

Monivs答案的伟大工程,如果你想直接打开PDF浏览器,你可以做这样的:

MemoryStream ms = new MemoryStream(documentBody); 
var response = new Response(); 
response.ContentType = "application/pdf"; 
response.Contents = stream => { 
    ms.WriteTo(stream); 
}; 
return response;