2

是否可以在返回视图之前获取 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;
            };
4

3 回答 3

4

小心!这个答案基于 nancy 版本0.11,从那时起发生了很多变化。路线中的版本应该仍然有效。如果您使用内容协商,则不是后续管道中的那个。

您可以将内容写入路由中的内存流,也可以将委托添加到 After Pipeline:

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.
               }
           }
        };
    }
}
于 2012-07-27T09:26:01.850 回答
1

View[]返回一个Response对象并具有Content该类型的属性,Action<Stream>因此您可以将 a 传递MemoryStream给委托,它将在该流中呈现视图

于 2012-07-27T10:20:26.983 回答
1

我使用 Nancy 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...

           };

    }
}
于 2013-07-18T09:20:14.000 回答