最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Object lifecycle changes between .net 4.7 and 4.8 versions of System.Net.Http - Stack Overflow

programmeradmin5浏览0评论

I'm working on upgrading a very large legacy solution from 4.7 to 4.8. It's not been a problem on the whole but now all the projects are upgraded, I've got one failing unit test which is giving me cause for concern. No code has changed - only the framework versions.

The code that's being tested is this:

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);
    }
}

The unit test that's failing mocks the HttpResponseObject to return a 404, and checks that the method throws an exception of type OurCustomExceptionClass.

What's worrying me is that instead of that exception, the code is now throwing an System.ObjectDisposedException at httpRequestMessage.Content.ReadAsStringAsync(). The full error message is:

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

So I'm concerned there's been a change in how System.Net.Http handles and maintains requests between 4.7 and 4.8 which might be impactful in active usage.

Can anyone explain if there has been such a change, and why it's causing this test to fail? Is it something I need to worry about for live use, or can I just fix the test and move on?

发布评论

评论列表(0)

  1. 暂无评论