C# System.Net.Http 无法识别定义

C# System.Net.Http Not recognizing definitions

(我使用的是 Visual Studio 2015)

我从另一个 VS 项目中复制了这个函数(效果很好)。我注意到我在 tokenClient.SetBasicAuthentication() 处遇到错误。

然后我从工作代码中意识到这是在引用 System.Net.Http

所以我通过 Add -> References 添加了参考。

我仍然遇到错误。所以我去寻找Nuget包并安装了System.Net.Http v4.3.4(微软)。

我仍然收到此错误。 (见图 - 我还包含了代码)。

有人可以帮忙吗?为什么我无法让 SetBasicAuthentication 工作?

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Authentication;
using System.Threading.Tasks;
using System.Web;

// other code ......
// other code ......

public static async Task<string> querySite(string url)
{
    var tokenClient = new HttpClient();
    var postData = new FormUrlEncodedContent(new Dictionary<string, string>() { { "grant_type", "client_credentials" }, { "scope", "site_integration_api" } });

    //Create TLS Security Protocol
    ServicePointManager.SecurityProtocol = Tls12;
    tokenClient.SetBasicAuthentication(clientID, clientSecret);

    var tokenResponse = await tokenClient.PostAsync(loginUrl, postData);
    if (!tokenResponse.IsSuccessStatusCode)
        throw new ApplicationException("Could not accept token. Ensure credentials are correct.");

    string tokenData = await tokenResponse.Content.ReadAsStringAsync();

    int start = tokenData.IndexOf(access_token_string) + access_token_string.Length + 1;
    int end = tokenData.IndexOf("\"", start + 1) - start;
    var accessToken = tokenData.Substring(start, end);

    //Call service to get XML
    var serviceClient = new HttpClient();
    serviceClient.SetBearerToken(accessToken);

    return await serviceClient.GetStringAsync(url);        
}

您可以为基本身份验证创建自己的扩展方法:

public static class HttpClientExtention
{
    public static void SetBasicAuthentication(this HttpClient client, string userName, string password)
    {
        client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Basic",
                Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes($"{userName}:{password}")));
    }
}