'How to use PostAsync() Request in a Loop?
I need send a POST for each object on a List<>.
This is the main function that sends the post
public async Task<string> Set(int pessoaId)
{
try
{
Pessoas pessoa = new PessoasBLL().SelectBy("PessoaID", pessoaId);
List<Endereco> lstEndereco = new EnderecoBLL().SelectByEntidade(pessoaId);
Person person = new Person();
person = SerializePerson(person, pessoa, lstEndereco);
string token = new IntegracaoBLL().Select().ToUpper();
// Put the following code where you want to initialize the class
// It can be the static constructor or a one-time initializer
if (client.BaseAddress == null)
{
client.BaseAddress = new Uri(baseURL);
}
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", token);
var data = JsonConvert.SerializeObject(person);
var request = new StringContent(JsonConvert.SerializeObject(person), Encoding.UTF8, "application/json");
var postResponse = await client.PostAsync("person", request);
if (postResponse.StatusCode == HttpStatusCode.Created || postResponse.StatusCode == HttpStatusCode.NotAcceptable)
{
new PessoasBLL().SetImportacao(pessoaId, true);
}
return null;
}
catch (Exception ex)
{
return null;
}
}
The function work as fine when not in a loop, like this for example:
private void btnTeste_Click(object sender, EventArgs e)
{
new IntegrationWebApi().Set(8).ConfigureAwait(true);
}
But I'm having trouble getting this 'code' to work in a loop, like this for example
private void btnTeste_Click(object sender, EventArgs e)
{
try
{
List<Pessoas> pessoas = new PessoasBLL().SelectAllIntegracao();
foreach (Pessoas p in pessoas)
{
new IntegrationWebApi().Set(p.ID).ConfigureAwait(true);
}
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
new Logger().LogEntry(ex);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
