You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 4.7升级至4.8后System.Net.Http中请求内容对象提前释放引发ObjectDisposedException问题咨询

.NET 4.7升级至4.8后System.Net.Http中请求内容对象提前释放引发ObjectDisposedException问题咨询

我正在把一个大型的遗留解决方案从.NET 4.7升级到.NET 4.8,整体过程都挺顺利,但所有项目升级完成后,有一个单元测试失败了,这让我有点担心——没有修改任何业务代码,只升级了框架版本。

被测试的代码如下:

var httpRequestMessage = new HttpRequestMessage
{
    Method = HttpMethod.Post,
    RequestUri = new Uri($"{this.options.Value.OurInternalObjectProperty}{this.licenseKey}&Content-Type=application-JSON"),
    Headers =
    {
        { HttpRequestHeader.Accept.ToString(), "application/json" },
        { "token", this.licenseKey },
        { "projectName", this.options.Value.OurInternalObjectProperty }
    },
    Content = new StringContent(JsonConvert.SerializeObject(ourObjectParameter))
};

using (var response = await this.httpClient.SendAsync(httpRequestMessage))
{
    if (response.IsSuccessStatusCode)
    {
        var result = await this.DeserialiseObject<OurInternalObjectResult>(response);
        return Task.FromResult(result).Result;
    }
    else
    {
        var requestHeaders = $"token: {this.licenseKey}, projectName: {this.options.Value.OurInternalObjectProperty }";
        var requestBody = await httpRequestMessage.Content.ReadAsStringAsync();
        var responseBody = await response.Content.ReadAsStringAsync();
        this.logger.LogWarning(message: $"Our error message");
        throw new OurCustomExceptionClass(responseBody, (int)response.StatusCode);
    }
}

这个失败的单元测试会模拟HttpResponse返回404状态码,然后验证方法是否会抛出OurCustomExceptionClass类型的异常。

但现在的问题是,代码没有抛出预期的异常,反而在执行httpRequestMessage.Content.ReadAsStringAsync()时抛出了**System.ObjectDisposedException**,完整的错误信息是:

'Cannot access a disposed object. Object name: 'System.Net.Http.StringContent'.'

我担心这是.NET 4.7到4.8之间,System.Net.Http处理和维护请求的机制发生了变化,而且这个变化可能会影响生产环境的正常使用。

有没有人能解释一下,这两个版本之间确实存在这样的变更吗?为什么会导致这个测试失败?这是我需要在生产环境中关注的问题,还是说我只需要修复测试就可以了?

备注:内容来源于stack exchange,提问作者Bob Tway

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 10:45:28