首页 > 解决方案 > C# HttpClient() getStringASync() 404 (Not Found)

问题描述

So i'm trying to make a basic Console Application that simply gets the visible text on the webpage. But for example, if the page is not found, i'm getting an error. I'm not sure how i'd be able to fix this error, like, if it errors i want it to just ignore it. I tried adding a if statement but it does the exact same.

HttpClient client = new HttpClient();
string content = await client.GetStringAsync("https://www.yourwebsite.com/);

标签: c#

解决方案


所以你可以捕获 HttpRequestException,但我的建议是不要使用 GetStringAsync 更好的方法是使用 GetAsync 方法

HttpClient client = new HttpClient();
var response = await client.GetAsync("https://www.yourwebsite.com");
if (response.IsSuccessStatusCode) {
  var getResponsestring = await response.Content.ReadAsStringAsync();
}
else {
  ... your logic here 

}

推荐阅读