Я начинаю работать с XamarinForms и столкнулся с странной проблемой.
Поток приложений выглядит так:
- Со страницы (NewExpensePage.cs) Я открываю модальное (push async) для операции Create
- Страница имеет BindingContext с ViewModel (ExpenseViewModel.cs)
- Команда кнопки связана с Командой (SaveExpenseCommand) в классе ViewModel, которая будет вызывать метод в Сервисе (IBTService.cs), который, в свою очередь, выдаст запрос HttpPost.
Код страницы позади:
public partial class NewExpensePage : ContentPage
{
private readonly ExpenseViewModel viewModel;
public NewExpensePage(int currentGroupId)
{
InitializeComponent();
viewModel = new ExpenseViewModel(currentGroupId);
this.BindingContext = viewModel;
// let this page know save op has completed, and the close the modal
MessagingCenter.Subscribe<ExpenseViewModel>(this, "save-completed", async (i) => { await Navigation.PopModalAsync(); });
}
}
Код модели представления:
public class ExpenseViewModel : BaseViewModel
{
/* ... */
public Command SaveExpenseCommand { get; set; }
private readonly int CurrentGroupId;
public ExpenseViewModel(int selectedGroupId)
{
CurrentGroupId = selectedGroupId;
this.LoadCategoriesCommand = new Command(async () => await LoadCategories());
this.SaveExpenseCommand = new Command(async () => await SaveExpense());
}
async Task SaveExpense()
{
Item.ExpenseCategoryId = SelectedCategory.Id;
await IBTService.SaveExpense(Item);
MessagingCenter.Send(this, "save-completed");
}
}
И, наконец, метод в Сервисном коде (IBTService.cs):
public async Task<bool> SaveExpense(Expense model)
{
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(api);
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
var dbModel = new ApiExpense
{
Amount = model.Amount,
Date = model.Date.ToString("dd-MM-yyyy", CultureInfo.InvariantCulture),
ExpenseCategoryId = model.ExpenseCategoryId,
Description = model.Description
};
// HERE: Debugger runs out to caller method (back in view model) without waiting for this to complete
var response = await httpClient.PostAsync("api/Expenses/PostExpense", new StringContent(JsonConvert.SerializeObject(dbModel)));
if (response.IsSuccessStatusCode)
{
return true; //temp solution
}
return false;
}
}
Проблема здесь начинается с var response = await httpClient.PostAsync...
в последней части кода, где отладчик выпадает из выполнения, как только выполняет этой строки, без * ожидания для этого результата для завершения.
Буду признателен за любую помощь!