【问题标题】:Dispose HTTP response in .NET WebAPI在 .NET WebAPI 中处理 HTTP 响应
【发布时间】: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


【解决方案1】:

你可以使用ApiController.OK

return Ok(myResult);

您不应使用 using (var response = Request.CreateResponse(HttpStatusCode.OK)),因为 ResponseMessageResult 将持有对已处理 HttpResponseMessage 的引用。这就是您在断言中收到此错误的原因。

要检查,请将代码更改为下面的 sn-p 并在结果上添加断点。检查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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-19
    • 2012-09-12
    • 2014-07-31
    • 2016-02-29
    • 2015-04-27
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多