C# WebClient.DownloadString抛出一个';System.Net.WebException';
WebClient.DownloadString每次运行时都会失败,在System.dll中引发“System.Net.WebException”。它的名称有什么问题吗?代码如下C# WebClient.DownloadString抛出一个';System.Net.WebException';,c#,html,.net,webclient,C#,Html,.net,Webclient,WebClient.DownloadString每次运行时都会失败,在System.dll中引发“System.Net.WebException”。它的名称有什么问题吗?代码如下 using (var wc = new WebClient()) { wc.Headers["Authorization"] = string.Format("Basic {0}", ConfigurationManager.AppSettings["which_
using (var wc = new WebClient())
{
wc.Headers["Authorization"] = string.Format("Basic {0}", ConfigurationManager.AppSettings["which_api_token"]);
try
{
var jsonString = wc.DownloadString(string.Format("{0}/subjects/{1}",
ConfigurationManager.AppSettings["which_api_url"],
Uri.EscapeDataString(subjectName)));
return result;
}
catch(Exception ex)
{
result.Status = ResultStatus.Failed;
return result;
}
}
WebException为您提供了错误信息
using (var wc = new WebClient())
{
wc.Headers["Authorization"] = string.Format("Basic {0}", ConfigurationManager.AppSettings["which_api_token"]);
try
{
var jsonString = wc.DownloadString(string.Format("{0}/subjects/{1}",
ConfigurationManager.AppSettings["which_api_url"],
Uri.EscapeDataString(subjectName)));
return result;
}
catch(Exception ex)
{
WebException we = ex as WebException;
if (we != null && we.Response is HttpWebResponse)
{
HttpWebResponse response = (HttpWebResponse)we.Response;
// it can be 404, 500 etc...
Console.WriteLine(response.StatusCode);
}
result.Status = ResultStatus.Failed;
return result;
}
}
异常的消息是什么?也许可以解释一下,你没有做任何关于
异常的事情
你正在“捕捉”。。。将这行代码插入catch块抛出新异常(例如Message)
并去掉返回的结果代码>这将使您更好地理解错误(这次请不要忘记与我们分享错误)