【发布时间】:2018-07-05 14:13:29
【问题描述】:
我创建了 Xamarin 项目,并向其中添加了几个 .Net 标准类库(每一层一个:数据访问、服务层等)。然后,在 ServiceLayer 项目中,我实现了从我的 Web API(外部 ASP Net Core 项目)获取数据的方法。当涉及到 httpClient.GetAsync() 时,android 应用程序崩溃。更重要的是,当我剪切这段代码并将其粘贴到默认的 xamarin .Net 标准库中时,一切正常。有任何想法吗?
代码在这里:
HttpClient httpClient = new HttpClient();
var responseMessage = await httpClient.GetStringAsync(uri);
更新:
在视图模型中:
constructor(IServiceLayerService service){
_ServiceLayerService = service;
GetTestCommand = new DelegateCommand(async () => await GetTests());
}
public async Task GetTests()
{
TestObservableCollection = new ObservableCollection<List<Test>>(await _ServiceLayerService.GetTestModels());
}
更新 2: 我已经按照第一个答案中介绍的方式更改了我的异步方法调用。现在,当我尝试执行代码时,应用程序也崩溃了,但我收到了错误消息:
07-05 14:39:04.518 F/ (25383): /Users/builder/jenkins/workspace/xamarin-android-d15-7/xamarin-android/external/mono/mono/mini/debugger-agent.c:4897: Could not execute the method because the containing type is not fully instantiated. assembly:<unknown assembly> type:<unknown type> member:(null) signature:<none>
07-05 14:39:04.518 F/libc (25383): Fatal signal 6 (SIGABRT), code -6 in tid 25383 (com.companyname), pid 25383 (com.companyname)
也许我在Unity依赖注入方面做错了,所以这里是在App.xaml.cs中注册服务层类
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation<NavigationPage>();
containerRegistry.RegisterForNavigation<TestsListPage, TestsListViewModel>();
containerRegistry.Register<IServiceLayerService, ServiceLayerService>();
}
【问题讨论】:
-
当代码崩溃时如何以及在哪里被调用?您是否在拨打
.Result或.Wait()之类的阻塞电话? -
我将 ServiceLayer 项目中的类注入 ViewModel,然后在命令中执行它。
-
显示。很可能您的命令中有一个异步 void 不允许您捕获异常。
-
我已经用代码更新了问题
-
是的
GetTestCommand = new DelegateCommand(async () => await GetTests());创建一个异步 void。创建一个事件处理程序并在命令中引发它。
标签: c# rest xamarin dotnet-httpclient