Dot-Net
NancyFX:反序列化 JSON
該文件建議 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; } } }
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; } }