2012-05-23 7 views
7

Die Dokumentation schlägt vor, die NancyFx hilft mir WRT Deserialisierung von JSON Anfrage Körper, aber ich bin mir nicht sicher, wie. Siehe Test unten zu demonstrieren: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; } 
    } 
} 

Antwort

15

Model-binding

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

EDIT (um oben in Zusammenhang zugunsten von anderen Lesern dieser Frage)

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

Verstanden, danke, einfach und elegant. Ich verliebe mich in Nancy. –

+0

Gibt es eine Voraussetzung für die Serialisierung? Ich übergebe eine gültige JSON-Zeichenfolge, aber mein dynamisches Objekt hat keine Schlüssel oder Werte. –