3

すべてのルートが呼び出された後にモデルを変更できるAfterRequestイベント ハンドラーを myに追加したいと考えています。これは可能ですか?モデルにアクセスできるプロパティが Response に表示されません (存在する場合)。Bootstrapper.csResponse

これが私の使用例です(から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

1

それほど単純ではないと思います。どのデシリアライザーが使用され、どのオブジェクトが返されているかを知るために、ctx.Response.Content を調べる必要があります。Json としてシリアル化された Foo オブジェクトを返す簡単な例を作成しました.....

    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 に答える