C# 执行HttpRequest后跳过代码
因此,我正在对我的API进行POST调用,以获取多个对象,然后将这些对象添加到列表中,并显示在RecyclerView中。问题是,在获得var结果后,它跳过该方法中的所有剩余代码,并执行下一个方法SetupRecyclerView。捕获未捕获任何异常。那代码怎么了C# 执行HttpRequest后跳过代码,c#,http,xamarin,android-recyclerview,webapi,C#,Http,Xamarin,Android Recyclerview,Webapi,因此,我正在对我的API进行POST调用,以获取多个对象,然后将这些对象添加到列表中,并显示在RecyclerView中。问题是,在获得var结果后,它跳过该方法中的所有剩余代码,并执行下一个方法SetupRecyclerView。捕获未捕获任何异常。那代码怎么了 async void GetPostList() { try { string url = "linkToMyWebServic
async void GetPostList()
{
try
{
string url = "linkToMyWebService";
var uri = new Uri(url);
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = uri
};
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
HttpClient client = new HttpClient(clientHandler);
var result = await client.SendAsync(request);
var contentBody = await result.Content.ReadAsStringAsync();
List<postRetrieved> posts = JsonConvert.DeserializeObject<List<postRetrieved>>(contentBody);
foreach (var post in posts)
{
postModel newPost = new postModel();
newPost.username = post.fullName;
newPost.description = post.postTitle;
newPost.city = post.postCity;
postList.Add(newPost);
}
}
catch
{
}
}
void SetupRecyclerView()
{
postRecyclerView.SetLayoutManager(new Android.Support.V7.Widget.LinearLayoutManager(postRecyclerView.Context));
postAdapter = new PostAdapter(MainScreenPosts);
postRecyclerView.SetAdapter(postAdapter);
}
async void GetPostList()
{
尝试
{
字符串url=“linkToMyWebService”;
var uri=新的uri(url);
var请求=新的HttpRequestMessage
{
方法=HttpMethod.Post,
RequestUri=uri
};
HttpClientHandler clientHandler=新的HttpClientHandler();
clientHandler.ServerCertificateCostomValidationCallback=(发送方、证书、链、sslPolicyErrors)=>{return true;};
HttpClient=新的HttpClient(clientHandler);
var result=wait client.sendaync(请求);
var contentBody=wait result.Content.ReadAsStringAsync();
List posts=JsonConvert.DeserializeObject(contentBody);
foreach(var post in post)
{
postModel newPost=新的postModel();
newPost.username=post.fullName;
newPost.description=post.postTitle;
newPost.city=post.postCity;
postList.Add(newPost);
}
}
抓住
{
}
}
void SetupRecyclerView()
{
SetLayoutManager(新的Android.Support.V7.Widget.LinearLayoutManager(postRecyclerView.Context));
postAdapter=新的postAdapter(主屏幕帖子);
postRecyclerView.SetAdapter(postAdapter);
}
很可能是关于捕获。返回了一些错误,一个空的catch会导致跳过该方法。
您可以在“异常设置”中启用“公共语言运行时异常”,也可以在捕获中记录错误。这将帮助您获得有关代码错误的更多详细信息。好的,问题在于GetPostList是异步的。在等待获取对象列表的请求时,它开始执行SetupRecyclerView方法,该方法要求这些对象正常工作。我已经把它放在trycatch的Finally{}块中,现在它可以正常工作。空的catch块将使您很难知道代码何时抛出错误。至少要记录错误。如果您不打算处理异常,请不要默默地捕获它并像那样扔掉错误。这只会使调试代码变得更加困难。这可能就是正在发生的事情。您的代码可能会抛出一个异常,该异常会被悄悄地丢弃。执行将在
catch
块关闭后恢复。如果没有关于异常的具体信息,我们无法进一步诊断它。