【发布时间】:2017-02-10 10:48:54
【问题描述】:
我有一个.NET WebAPI 应用程序,这是我的 api 之一:
public IHttpActionResult Get()
{
...building myResult here...
var content = ElasticSearch.Json.ToJson(myResult);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(content, Encoding.UTF8, "application/json");
return ResponseMessage(response);
}
我从代码分析中收到 CA2000 错误:
错误 CA2000 在方法 'GroupsController.Get(string, string, string, bool, string)',调用 System.IDisposable.Dispose 对象'response' 在所有对它的引用都没有之前 范围
所以我修改了这样的代码:
var content = ElasticSearch.Json.ToJson(myResult);
using (var response = Request.CreateResponse(HttpStatusCode.OK))
{
response.Content = new StringContent(content, Encoding.UTF8, "application/json");
return ResponseMessage(response);
}
到目前为止一切顺利。没有内存泄漏,代码分析器又开心了。 不幸的是,现在我的一项测试抱怨它无法再访问已处理的对象。这里是测试那个 api 的测试(只是最后一部分):
// Assert
var httpResponseMessage = await result.ExecuteAsync(CancellationToken.None);
var resultJson = await httpResponseMessage.Content.ReadAsStringAsync();
Assert.AreEqual(expectedJson, resultJson);
Assert() 抱怨它无法访问已经释放的对象,这是实际的 api 结果:
System.ObjectDisposedException:无法访问已处置的对象。 对象名称:'System.Net.Http.StringContent'。在 System.Net.Http.HttpContent.CheckDisposed() 在 System.Net.Http.HttpContent.ReadAsStringAsync()
我该如何解决这个问题?处理对象似乎是合理的,但同时测试应该能够访问它
【问题讨论】:
-
您能否确保 httpResponseMessage 包含成功响应。如果请求失败,所有内容都将被处理,在这种情况下,您会遇到此问题。只需调试测试并在下一行之前查看您在 httpResponseMessage 中的内容。这也有助于在这里了解到底发生了什么。
标签: c# http asp.net-web-api