我是否错误地滥用了 HttpClient 类。我正在尝试测试图像的 HTTP 状态,但它似乎根本没有执行。我有一个复杂对象的列表,所以我想对所有图像 url 运行测试,以查看哪些 url 被破坏:
var client = new HttpClient();
var tasks = ObjectViewModel.Select(a => a.UserUrl).Select(url =>
client.GetAsync(url).ContinueWith(t =>
{
var response = t.Result;
if (!response.IsSuccessStatusCode)
url = "/Content/Images/MissingPic.png";
}));
我最初是在 foreach 循环中这样做的,如下所示:
foreach(var Model in ObjectViewModel)
{
Model.UserUrl= Model.UserUrl.GetHttpRequest() ? Model.UserUrl:
"/Content/Images/MissingImage.png";
//Model.state= Model.state.ValidName();// this line is something seperate
//Model.property= Model.state.propertyCheck();// this line is something seperate
}
public static bool GetHttpRequest(this string s)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest
.Create(s);
webRequest.AllowAutoRedirect = false;
HttpStatusCode responseStatusCode;
try
{
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
responseStatusCode = response.StatusCode;
}
catch (WebException we)
{
responseStatusCode = ((HttpWebResponse)we.Response).StatusCode;
}
if (responseStatusCode.ToString() == "OK")
return true;
else
return false;
}
这工作得很好,但完成所有项目大约需要 5 到 7 秒,因为它们都是单独运行的,这对于响应 UI 的请求来说非常长。