HttpClient请求即使无效网址也返回200 OK

时间:2020-07-30 22:20:26

标签: c# http-headers dotnet-httpclient

我正在验证网址,我的代码有问题,即使该网址无效,我也会收到200 OK响应。这是我的代码:

            var urlFormatted = "http://sfgsfgsg";
            Uri uri;
            if (!Uri.TryCreate(urlFormatted, UriKind.Absolute, out uri))
            {
                return Json(new { error = "Please enter a valid url" });
            }
            using (var client = new HttpClient())
            {                    
                client.DefaultRequestHeaders.Add("User-Agent", @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36");
                var response = await client.GetAsync(urlFormatted);
                string textResult = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    return Json(new { response = "success" });
                }
                else
                {
                    return Json(new { error = "Please enter a valid url" });
                }
            }

我查看了变量textResult的值,得到的是来自Internet中默认搜索引擎的搜索查询?这是textResult的值:"<html><head><meta http-equiv=\"refresh\" content=\"0;url=http://search.frontier.com/search/?q=http://sfgsfgsg%2F&bc=\"/></head><body><script type=\"text/javascript\">window.location=\"http://search.frontier.com/search/?q=\"+escape(window.location)+\"&r=\"+escape(document.referrer)+\"&bc=\";</script></body></html>"

如何获取404并防止该行为?网址有效时我没有问题。

请求响应的屏幕截图: enter image description here

0 个答案:

没有答案