C# 在.NET WebAPI中处理HTTP响应
我有一个C# 在.NET WebAPI中处理HTTP响应,c#,http,asp.net-web-api,C#,Http,Asp.net Web Api,我有一个.NET WebAPI应用程序,这是我的api之一: public IHttpActionResult Get() { ...building myResult here... var content = ElasticSearch.Json.ToJson(myResult); var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringCo
.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
错误:
方法“GroupsController.Get”(字符串,字符串,字符串,
bool,字符串“”,对对象“响应”调用System.IDisposable.Dispose
在所有对它的引用都被删除之前
范围
所以我修改代码如下:
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()
抱怨它无法访问已处理的对象,这是实际的api结果:
System.ObjectDisposedException:无法访问已处置的对象。
对象名称:“System.Net.Http.StringContent”。在
System.Net.Http.HttpContent.CheckDisposed()位于
System.Net.Http.HttpContent.ReadAsStringAsync()
我怎样才能解决这个问题?处理对象似乎是合理的,但同时测试应该能够访问它您可以使用ApiController.OK
return Ok(myResult);
您不应该使用using(var response=Request.CreateResponse(HttpStatusCode.OK)),因为ResponseMessageResult将保留对已处理的HttpResponseMessage的引用。这就是在assert中出现此错误的原因
若要检查,请将代码更改为下面的代码段,并在结果上添加断点。检查result.Response.disposed
using (var response = Request.CreateResponse(HttpStatusCode.OK))
{
response.Content = new StringContent(content, Encoding.UTF8, "application/json");
result = ResponseMessage(response);
}
// result.Response.disposed is true hence error in assert.
return result;
您可以使用ApiController.OK
return Ok(myResult);
您不应该使用using(var response=Request.CreateResponse(HttpStatusCode.OK)),因为ResponseMessageResult将保留对已处理的HttpResponseMessage的引用。这就是在assert中出现此错误的原因
若要检查,请将代码更改为下面的代码段,并在结果上添加断点。检查result.Response.disposed
using (var response = Request.CreateResponse(HttpStatusCode.OK))
{
response.Content = new StringContent(content, Encoding.UTF8, "application/json");
result = ResponseMessage(response);
}
// result.Response.disposed is true hence error in assert.
return result;
您能否确保httpResponseMessage包含成功响应。在请求失败的情况下,一切都将被处理,在这种情况下,您就有这个问题。只需调试测试并在下一行之前查看httpResponseMessage中的内容。这也有助于在这里使用,以了解到底发生了什么。您能否确保httpResponseMessage包含成功的响应。在请求失败的情况下,一切都将被处理,在这种情况下,您就有这个问题。只需调试测试并在下一行之前查看httpResponseMessage中的内容。这也有助于我们在这里了解到底发生了什么。