2012-05-23 27 views
7

Tài liệu này gợi ý rằng NancyFx giúp tôi thực hiện việc xóa bỏ WRT deserialization của cơ thể yêu cầu json, nhưng tôi không chắc chắn làm thế nào. Xem xét nghiệm dưới đây để chứng minh:NancyFX: Deserialize 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; } 
    } 
} 

Trả lời

15

Model-binding

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

EDIT (đặt trên vào bối cảnh vì lợi ích của độc giả khác của câu hỏi này)

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

Got nó, cảm ơn, đơn giản và tao nhã. Tôi yêu Nancy. –

+0

Có bất kỳ điều kiện tiên quyết nào để được sắp xếp theo thứ tự không? Tôi chuyển một chuỗi JSON hợp lệ nhưng đối tượng động của tôi không có khóa hoặc giá trị. –

Các vấn đề liên quan