0

I'm posting a bytearray from an Android App in Xamarin.Forms to an .NET Core 2.0 WebAPI. However, I'm getting an exception saying that the NetworkStream already is disposed;

Code making the request;

public async Task PostImageAsync(ImageDTO image)
{
    var content = new MultipartFormDataContent();
    var byteArrayContent = new ByteArrayContent(image.Content);
    content.Add(byteArrayContent, image.FileTile, image.FileName);

    try
    {
        using (var httpClient = GetNewHttpClient())
        {
            SetBearerToken(httpClient);

            var response = await httpClient.PostAsync($"{_apiUrl}/api/images/upload", content);
            if (response.IsSuccessStatusCode)
            {

            }
            else
            {

            }
        }
    }
    catch (Exception e)
    {
        //Exception occurs here
        var msg = e.GetBaseException().Message;

        throw;
    }
}

Code to get the HttpClient

private HttpClient GetNewHttpClient()
{
     //HttpClientHandler is a global variable                
     var httpClient = new HttpClient(HttpClientHandler, false) {BaseAddress = new Uri(_apiUrl)};

    return httpClient;
}

API Endpoint

[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
    if (file == null || file.Length == 0) return BadRequest();

    return Ok();
}

EDIT - SetBearerToken Method

private static void SetBearerToken(HttpClient client)
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", App.StoredToken);
        }

The Exception:

cannot access a disposed object. Object name: 'System.Net.Sockets.NetworkStream'.

It feels like a really obvious mistake I'm making here, but I can't get my head around it. Anybody has any ideas?

Rob
  • 6,731
  • 12
  • 52
  • 90

2 Answers2

1

Don't dispose objects inside async functions

A using statement in an async method is "odd" in that the Dispose call may execute in a different thread to the one which acquired the resource (depending on synchronization context etc) but it will still happen... assuming the thing you're waiting for ever shows up or fail, of course. (Just like you won't end up calling Dispose in non-async code if your using statement contains a call to a method which never returns.)

@jon-skeet https://stackoverflow.com/a/16566605/2228916

Mahmoud Samy
  • 2,822
  • 7
  • 34
  • 78
0

Don’t dispose of the HttpClient:

https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

Also noticed that you set _apiUrl as the BaseAddress and prefix the url in the post. Pick one or the other.

BFK
  • 69
  • 2
  • 7