3

我想向我添加一个AfterRequest事件处理程序Bootstrapper.cs,它能够在Response调用每个路由后修改模型。这可能吗?我在响应中看不到任何可以访问模型的属性(如果有的话)。

这是我的示例用法(来自Bootstrapper.cs):

 protected override void ApplicationStartup(..., IPipelines pipelines)
 {
    ...
    pipelines.AfterRequest += ModifyModel;
 }

 private void ModifyModel(NancyContext ctx)
 {
    // do things to the response model here
 }
4

3 回答 3

3

如果您仍然需要此功能,您可能会对我刚刚在 Nuget 上发布的扩展感兴趣:https ://www.nuget.org/packages/Nancy.ModelPostprocess.Fody 。我们的项目需要类似的功能

这将允许您在路线已经执行后修改您的模型。请查看Bitbucket 页面上的描述

请告诉我这是否适合您的需求。

于 2014-01-30T16:44:14.627 回答
1

我认为不是那么简单,您应该检查 ctx.Response.Content 以了解使用了哪个反序列化器以及您返回的是什么对象,我做了一个简单的示例,返回一个 Foo 对象序列化为 Json .....

    public class MyBootstrapper : Nancy.DefaultNancyBootstrapper
    {
        protected override void ApplicationStartup(TinyIoC.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            pipelines.AfterRequest += ModifyModel;
        }

        private void ModifyModel(NancyContext ctx)
        {
            Foo foo;
            using(var memory = new MemoryStream())
            {
                ctx.Response.Contents.Invoke(memory);

                var str = Encoding.UTF8.GetString(memory.ToArray());
                foo = JsonConvert.DeserializeObject<Foo>(str);
            }

            ctx.Response.Contents = stream =>
            {
                using (var writer = new StreamWriter(stream))
                {
                    foo.Code = 999;
                    writer.Write(JsonConvert.SerializeObject(foo));
                }
            };
        }
    }

    public class HomeModule : Nancy.NancyModule
    {
        public HomeModule()
        {

            Get["/"] = parameters => {
                return Response.AsJson<Foo>(new Foo { Bar = "Bar" });
            };
        }
    }

    public class Foo
    {
        public string Bar { get; set; }
        public int Code { get; set; }
    }
于 2013-10-01T08:06:12.077 回答
0

在对此进行了更多研究之后,这根本不可能(至少在合理范围内)与今天存在的 Nancy 框架有关。

于 2013-10-18T14:05:54.937 回答