【发布时间】:2014-08-27 16:52:50
【问题描述】:
我有一个与Conference API project 类似(几乎相同)的项目,它采用与上述项目类似的方法来返回 CollectionJson 内容。我很难设置 ReadDocument 的 Collection 属性(第 30 行),因为它没有任何设置器。我可以通过以下更改绕过这个问题
public CollectionJsonContent(Collection collection)
{
var serializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
Formatting = Newtonsoft.Json.Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
collection.Version = "1.0";
Headers.ContentType = new MediaTypeHeaderValue("application/vnd.collection+json");
using (var writer = new JsonTextWriter(new StreamWriter(_memoryStream)){CloseOutput = false})
{
//var readDocument = new ReadDocument(); {IReadDocument.Collection = collection};
var serializer = JsonSerializer.Create(serializerSettings);
serializer.Serialize(writer,collection);
writer.Flush();
}
_memoryStream.Position = 0;
}
虽然上面的代码可以编译并在一定程度上解决了问题,但我又会遇到另一个问题,即无法在我的控制器单元测试中使用 JsonCollection 内容。考虑以下单元测试代码 sn-p:
using (var request = CreateRequest())
{
var controller = new TestController(DataService) {Request = request};
var temp = await controller.ListAsync(gridSearchData, sampleSearchData);
if ((temp is NotFoundResult) && (sampleCollection.Any()))
{
Assert.Fail("Controller did not return any result but query did");
}
var json = await temp.ExecuteAsync(cancellationTokenSource);
var readDocument = json.Content.ReadAsAsync<ReadDocument>(new[] {new CollectionJsonFormatter()}, cancellationTokenSource).Result;
}
由于我没有设置 ReadDocument 的集合属性,所以 readDocument 总是空的,我无法读取它的内容。 WEB API项目中如何在客户端异步读取JsonCollection的内容?
要获得该方法的清晰图片,请查看Conference Web Api 和authors blog
【问题讨论】:
标签: c# json asp.net-web-api asp.net-web-api2 collection-json