Search code examples
c#copyhttpclientpass-by-value

Copy MultipartFormDataContent or pass it by value / Multiple send request with MultipartFormDataContent


I'm trying to send a post request with MultipartFormDataContent 2 times in a row. First time it works correct. But the next time compiler says me MultipartFormDataContent variable has allready disposed.

Tlg Tlg = new Tlg("MyToken");
MultipartFormDataContent options = new MultipartFormDataContent();
options.Add(new StringContent("MyChatId"), "chat_id");
options.Add(new StringContent("Hello!"), "text");
Console.WriteLine(Tlg.Send("sendMessage", options: options).Result);//ОК
Console.WriteLine(Tlg.Send("sendMessage", options: options).Result);//Fails

Tlg.Send just sends request via httpClient.PostAsync with MultipartFormDataContent variable (options).

How to realize multiple use of the MultipartFormDataContent variable with the least expenses?

Sorry for my English


Solution

  • Solution: I've just pass JObject parameters to function and then create new MultipartFormDataContent every call of function.

            MultipartFormDataContent o = new MultipartFormDataContent();
            if(options != null)
            {
                foreach (JProperty x in (JToken)options)
                {
                    o.Add(new StringContent((string)x.Value), x.Name);
                }
            }
    

    If it would be StreamContent or others, i'll add StreamContent.