如何在 .NET Framework 4.5 应用程序/网站中使用 HttpClient?

B. *_*non 2 asp.net http razor asp.net-4.5 dotnet-httpclient

基于这里的答案:How can Iretrieve and parse just the html returned from an URL?

...我尝试首先添加基于此处找到的代码:http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx

...即将其添加到 \App_Code\Functions.cshtml:

@functions
{
    public static string GetUrlHtml(string dynamicUrl)
    {
        HttpClient client = new HttpClient();
        string body = await client.GetStringAsync(dynamicUrl);
    // parse it using HTML Agility Pack? (http://htmlagilitypack.codeplex.com/)
    }
}
Run Code Online (Sandbox Code Playgroud)

HttpClient 无法识别,并且不提供“解析”上下文菜单项。输入后,Intellisense 不向我提供“Http”:

@using System.Net.
Run Code Online (Sandbox Code Playgroud)

HttpClient 真的对我不可用吗?如果可以的话,我能得到什么作为安慰奖呢?我最好的选择是像这样使用 WebClient:

WebClient wc = new WebClient();
string body = wc.DownloadString(dynamicUrl);
// parse it with html agility pack
Run Code Online (Sandbox Code Playgroud)

...或者,如https://web.archive.org/web/20211020001935/https://www.4guysfromrolla.com/articles/011211-1.aspx#postadlink所示,我可以使用 webGet 类HTML 敏捷包:

var webGet = new HtmlWeb();
var document = webGet.Load(dynamicUrl);
Run Code Online (Sandbox Code Playgroud)

有人对哪个选项最好有任何支持的意见吗?

reg*_*bsb 5

错误的答案将被接受。

这是正确的:

添加到配置中

<system.web>
    <compilation>
        <assemblies>
            <add assembly="System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        </assemblies>
    </compilation>
</system.web>
Run Code Online (Sandbox Code Playgroud)