I am Posting a JSON in .Net Maui to HTTPClient that works correctly the most time. But sometimes it fails.
I have RestService class that contains a method called PostJason and my code is inside try/catch but when it reaches the POST line, the cursor of the program dissapear and it doesn´t continues the program and never pass through catch.
I have tested it with a break point and that is the line that sometimes fails.
Repeat the most of the time that I call this method, it works Ok and the Post works fine… Maybe 1 in 30 times has an error.. I don´t post all my code because is very extensive…
The json parameter is passed when I call this class..
public static class JsonCreatorHelper
{
public static string CreateInvoiceJson(Order order)
{
var invoice = new
{
id = order.Id,
reference = order.Reference,
customer_id = order.Client.idEmpresa,
invoice_date = order.DateCreation.ToString("yyyy-MM-ddTHH:mm:ss.ffffffZ"),
importe_anticipo = order.AdvanceAmount,
lines = CreateOrderLinesJson(order.OrderLines)
};
return JsonConvert.SerializeObject(invoice, Formatting.Indented);
}
private static List<object> CreateOrderLinesJson(List<OrderLines> orderLines)
{
var lines = new List<object>();
foreach (var line in orderLines)
{
var lineJson = new
{
id = line.Id,
article_id = line.ProductId,
external_id = line.ProductId,
total = line.Total
};
lines.Add(lineJson);
}
return lines;
}
}
}
Could you tell me why can it happen and if there is any other way to solve this?
public static class RestService
{
//Fields
private static HttpClient _client;
private static JsonSerializerOptions _serializerOptions;
private const string _baseUrl = "https://abetekapimng.azure-api.net";
//Constructor
static RestService()
{
_client = new HttpClient();
_serializerOptions = new JsonSerializerOptions();
}
//Method
private static async Task PostJason(string endpoint, string json)
{
try
{
var url = $"{_baseUrl}{endpoint}";
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _client.PostAsync(url, content); //This is the line that sometimes fails; it doesn´t continue to next line or catch
response.EnsureSuccessStatusCode();
string responseContent = await response.Content.ReadAsStringAsync();
}
catch
{
await MessagesHelper.DisplayAlert("Error al sincronizar el albaran");
}`
I need to understand the problem