3

我有这样的方法的 WebAPI 实现:

 public IEnumerable<Device> GetAllDevices()
 public Device GetDeviceById(int id)

看起来不错,在 IIS 或自托管中运行时它可以工作。正确返回 JSON 对象。

但是,第一种方法在我尝试使用内存服务器的单元测试中失败。

 System.InvalidOperationException : Cannot create and populate list type System.Linq.IQueryable`1[Test.Device].

这归结为 Newtonsoft.Json.Serialization 程序集。测试示例如下:

        [Test]
    public void GET_AskingForListOfDevices_GettingOk200WithListOfDevicesInJSON()
    {
        var client = new HttpClient(InMemoryServer);
        HttpRequestMessage request = CreateRequest("api/devices", "application/json", HttpMethod.Get);

        using (HttpResponseMessage response = client.SendAsync(request).Result)
        {
            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            Assert.NotNull(response.Content);
            Assert.AreEqual("application/json", response.Content.Headers.ContentType.MediaType);

            // next line throws exc
            var content = response.Content.ReadAsAsync<IQueryable<Device>>().Result;

            Assert.AreEqual(3, content.Count());
        }

        request.Dispose();
    }

知道在哪里看吗?

更新
下面的示例引发了该错误,但是我找到了避免它的解决方案。只需使用 IList<> 而不是 IQueryable<>。仍然它没有回答我为什么它在 Fiddler 中工作的问题。它使用相同的技巧吗?

4

1 回答 1

2

我遇到了同样的情况。IQueryable 引发异常,但如果您使用 IEnumerable 则它可以工作。

于 2012-12-16T15:24:37.590 回答