我开始使用XamarinForms,但是遇到了 strange 问题。
应用流程如下:
后面的页面代码:
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(); });
}
}
ViewModel代码:
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...
,调试器在执行这一行时就跳出了执行程序,而没有 *等待 >完成此结果。
任何帮助将不胜感激!