是否可以在返回View之前获取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 :(得分:4)
小心!这个答案基于南希版 0.11 ,从那以后发生了很多变化。路线中的版本仍应有效。如果您使用内容协商,那么后续管道中的那个。
您可以将内容写入路径中的内存流,也可以添加委托 后管道:
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.
}
}
};
}
}
答案 1 :(得分:1)
View[]
返回一个Response
对象,其Content
属性类型为Action<Stream>
,因此您可以将MemoryStream
传入代理中将渲染该流中的视图
答案 2 :(得分: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...
};
}
}