c# - 在 Web Api 项目中读取 CollectionJson 内容

标签 c# json asp.net-web-api asp.net-web-api2 collection-json

我有一个与 Conference API project 相似(几乎相同)的项目它采用与返回 CollectionJson 内容的著名项目类似的方法。我在设置 ReadDocument 的 Collection 属性(第 30 行)时遇到困难,因为它没有任何 setter 。我可以通过进行以下更改来绕过这个问题

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;
}

虽然上面的代码编译并在某种程度上解决了问题,但我又会遇到另一个问题,即无法在我的 Controller 单元测试中使用 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的collection属性,readDocument总是空的,我无法读取它的内容。 WEB API项目中如何在客户端异步读取JsonCollection的内容?

要清楚地了解该方法,请查看 Conference Web Apiauthors blog

最佳答案

好的,已经解决了。 Collection 属性现在可以再次设置。

我刚刚推送了release 0.7.0有了这个修复,一个主要的命名重构以及对序列化的一个很好的改进不会写出空集合。

请参阅release notes对于更改(尤其是包名称和命名空间已更改的命名)

关于c# - 在 Web Api 项目中读取 CollectionJson 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25532841/

相关文章:

c# - HttpResponseMessage' 不包含 'GetAwaiter' 的定义并且没有可访问的扩展方法 'GetAwaiter'

javascript - Angular 多语言应用

JQuery Ajax 检索 JSON

c# - oData v4 (6.1.0) 在 $expand 中嵌套了 $filter

用于将操作应用于不同数量的对象的 C# 语法

c# - 将列表中的值分配给不包括空值的列表

c# - ASP.NET Core 3 API 忽略带有 Bearertoken 的授权属性

c# - 需要将 asp.net webapi 2 请求和响应正文记录到数据库

c# - 限制文本框中允许的字符(输入金额)

c# - 在 C# 中循环遍历 json 数组