2012-07-27 31 views
2

是否可以在返回視圖之前獲取NancyResponse正文?在返回視圖之前獲取NancyResponse內容正文

我的意思是這樣的:

Get["/"] = x => { 
       var x = _repo.X(); 
       var view = View["my_view", x]; 
       **//here I want to send the response body by mail** 
       return view; 
      }; 
+0

我看到是有一個「AsAttachment」擴展 – JackNova 2012-07-27 09:25:01

+0

這使得瀏覽器下載的響應。 – albertjan 2012-07-27 09:26:28

+0

是的,我看,它只覆蓋了類型 – JackNova 2012-07-27 09:27:18

回答

4

當心!這個答案是基於nancy版本0.11,自那以後發生了很多變化。路線內的版本仍然可以工作。如果您使用內容協商,那麼後面管道中的那個不是。

你可以寫的內容,一個MemoryStream的路線,或者你可以添加一個委託到 的管道後:

public class MyModule: NancyModule 
{ 
    public MyModule() 
    { 
     Get["/"] = x => { 
      var x = _repo.X(); 
      var response = View["my_view", x]; 
      using (var ms = new MemoryStream()) 
      { 
       response.Contents(ms); 
       ms.Flush(); 
       ms.Position = 0; 
       //now ms is a stream with the contents of the response. 
      } 
      return view; 
     }; 

     After += ctx => { 
      if (ctx.Request.Path == "/"){ 
       using (var ms = new MemoryStream()) 
       { 
        ctx.Response.Contents(ms); 
        ms.Flush(); 
        ms.Position = 0; 
        //now ms is a stream with the contents of the response. 
       } 
      } 
     }; 
    } 
} 
+0

似乎不錯,謝謝 – JackNova 2012-07-27 09:27:47

+0

不客氣。 – albertjan 2012-07-27 09:28:23

+0

它是'ctx.Request.Path' – JackNova 2012-07-27 09:29:54

1

View[]返回Response對象並擁有類型的Content財產Action<Stream>所以你可以傳入一個MemoryStream到委託,它會呈現該視圖中的視圖

1

我使用南希版本0.17和@albertjan解決方案是基於0.11。 由於@TheCodeJunkie他向我介紹了IViewRenderer

public class TheModule : NancyModule 
{ 
    private readonly IViewRenderer _renderer; 

    public TheModule(IViewRenderer renderer) 
    { 
      _renderer = renderer; 

      Post["/sendmail"] = _ => { 

       string emailBody; 
       var model = this.Bind<MyEmailModel>(); 
       var res = _renderer.RenderView(this.Context, "email-template-view", model); 

       using (var ms = new MemoryStream()) { 
        res.Contents(ms); 
        ms.Flush(); 
        ms.Position = 0; 
        emailBody = Encoding.UTF8.GetString(ms.ToArray()); 
       } 

       //send the email... 

      }; 

    } 
} 
相關問題