Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NancyFX : Deserialize JSON

The documentation suggests the NancyFx helps me out WRT deserialization of json request body, but I'm not sure how. See test below to demonstrate:

[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; }
    }
}
like image 873
Myles McDonnell Avatar asked May 23 '12 15:05

Myles McDonnell


1 Answers

Model-binding

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

EDIT (to put above into context for the benefit of other readers of this question)

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;
    }
}
like image 54
jjchiw Avatar answered Sep 22 '22 20:09

jjchiw