HttpClient HttpRequestException

时间:2013-02-28 18:38:05

标签: c# httpclient

我遇到HttpClient的问题,我一直在HttpRequestException occurred in mscorlib.dll。我已经从SVN下载了以前的工作版本,并且我一直得到相同的例外。

为什么我突然得到这个例外,即使我运行的代码已经运行好几周了?

现在我正在尝试使用这个简单的代码进行调试,但无论我做什么,我都会得到相同的异常

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept
    .Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(
              "application/json"));
HttpResponseMessage response
    = await client.GetAsync("http://api.themoviedb.org/3/movie/550?api_key=x");
return await response.Content.ReadAsStringAsync();

我的内部异常如下:

The remote name could not be resolved: 
    api.themoviedb.org System.Exception System.Net.WebException

我尝试的每个网址都是一样的,它们都在我的浏览器中工作。 这是异常和堆栈跟踪:

res "System.Net.Http.HttpRequestException: An error occurred while sending the request. 
---> System.Net.WebException: The remote name could not be resolved: 'api.themoviedb.org'
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotificat‌​ion(Task task)

1 个答案:

答案 0 :(得分:9)

这是您网络上的DNS问题。您的工作站(或收到错误的服务器)无法解析DNS名称“api.themoviedb.org”。此DNS名称可以从我的计算机和other networks online解析得很好。

请咨询您当地的网络管理员。

<强>更新

因此,您的机器可以解析名称,但HttpClient不能。让我们看看我们是否可以解决这个问题。我将假设这是一个桌面应用程序,而不是一个网站。如果我错了,请告诉我 - 还有一些额外的考虑因素。

您必须按照本指南启用网络跟踪:How to: Configure Network Tracing。您希望按照该链接的指定配置App.config文件。简而言之,您应该在配置文件中添加以下内容:

<configuration>
    <system.diagnostics>
        <sources>
            <source name="System.Net" tracemode="includehex" maxdatasize="1024">
                <listeners>
                    <add name="System.Net"/>
                </listeners>
            </source>
        </sources>
        <switches>
            <add name="System.Net" value="Verbose"/>
        </switches>
        <sharedListeners>
            <add name="System.Net"
                type="System.Diagnostics.TextWriterTraceListener"
                initializeData="network.log" />
        </sharedListeners>
        <trace autoflush="true"/>
    </system.diagnostics>
</configuration>

应更改值network.log以满足您的需求。继续这样做,看看输出文件。

现在,诀窍是使用该文件找出问题的原因。有关如何解释该文件的提示,请参阅Interpreting Network Tracing,但信息很少。我们正在寻找的是DNS无法解决的原因。因此,搜索该文件为“api.themoviedb.org”。如果你愿意,请用结果更新问题,我会看看我是否可以帮助你。

相关问题