2012-05-23 21 views
7

文檔建議NancyFx幫助我完成json請求體的WRT反序列化,但是我不知道如何。請參見下面的測試來證明:NancyFX:反序列化JSON

[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; } 
    } 
} 

回答

15

Model-binding

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

EDIT(把上面的來龍去脈對於這個問題的其他讀者的利益)

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; 
    } 
} 
+1

明白了,謝謝,簡單和優雅。我愛上了南希。 –

+0

o是否有序列化的先決條件?我傳遞一個有效的JSON字符串,但我的動態對象沒有鍵或值。 –