0

I have the following pretty simple class for sending some data to an external supplier, what seems to happen is at the point of the _httpClient.PostAsync call something(?) has already disposed of the StringContent objects -

public async Task<SendResponse> SendMessageAsync(SendRequest request)
{

    var httpContent = MapLocally(request);

    var response = await _httpClient.PostAsync("email/3/send", httpContent);
    var actualResponse = await HandleResponseAsync<SendResponse>(response, "message/send");        

    return _responseMapper.Map(actualResponse!);
}

private MultipartFormDataContent MapLocally(SendEmailRequest request)
{
    using var fromContent = new StringContent("beakersoft@gmail.com");
    
    return new MultipartFormDataContent
    {
        { fromContent, "from" },            
    };
}

I don't get passed the PostAsync line and it just exceptions with

System.Net.Http.HttpRequestException: Error while copying content to a stream.

and

ObjectDisposedException: Cannot access a disposed object.

If I remove the using statement in the fromContent variable then it works ok, and same if I move the declaration of the variable from the MapLocally method to the SendMessageAsync, declare it (along with its using statement) and pass it into MapLocally.

I dont want to not have the using statement in the MapLocally method as that throws compiler warnings, and I don't want my mapping code in the SendMessageAsync method either.

I cant really understand what's going on, anyone seen this before?

beakersoft
  • 2,316
  • 6
  • 30
  • 40

1 Answers1

0

Not surprising, as you're explicitly disposing the StringContent when MapLocally() returns by putting using in front of its declaration.

You could just remove using and it should be fine.

If you want to be slightly more clear about cleaning up the StringContent you remove MapLocally() and put the contents of it just above var response = ... instead, but in this case this isn't really necessary (and a simple PostAsync() does the same).

sellotape
  • 8,034
  • 2
  • 26
  • 30