我有一个与Conference API项目类似(几乎相同)的项目,该项目采用与上述项目类似的方法来返回 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 内容。考虑以下单元测试代码片段:
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 和作者博客