NancyFX:反序列化JSON

时间:2012-05-23 15:22:33

标签: .net json rest nancy

文档建议NancyFx帮助我对json请求体进行WRT反序列化,但我不确定如何。请参阅下面的测试以证明:

[TestFixture]
public class ScratchNancy
{
    [Test]
    public void RootTest()
    {
        var result = new Browser(new DefaultNancyBootstrapper()).Post(
            "/",
            with =>
                {
                    with.HttpRequest();
                    with.JsonBody(JsonConvert.SerializeObject(new DTO {Name = "Dto", Value = 9}));
                });

        Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
    }

    public class RootModule : NancyModule
    {
        public RootModule()
        {
            Post["/"] = Root;
        }

        private Response Root(dynamic o)
        {
            DTO dto = null;//how do I get the dto from the body of the request without reading the stream and deserializing myself?

            return HttpStatusCode.OK;
        }
    }

    public class DTO
    {
        public string Name { get; set; }
        public int Value { get; set; }
    }
}

1 个答案:

答案 0 :(得分:15)

Model-binding

var f = this.Bind<Foo>();

编辑(为了这个问题的其他读者的利益,将其置于上下文中)

public class RootModule : NancyModule
{
    public RootModule()
    {
        Post["/"] = Root;
    }

    private Response Root(dynamic o)
    {
        DTO dto = this.Bind<DTO>(); //Bind is an extension method defined in Nancy.ModelBinding

        return HttpStatusCode.OK;
    }
}