使用 HttpClient 获取

Using HttpClient to GET

所以,因为 HttpClient 是 "better,",所以我需要将 WebClient 转换为 HttpClient,但它没有按预期工作。下面的函数使用 WebClient 并且工作起来很有魅力。

private static void Authenticate()
{
    Console.WriteLine("Authenticating . . .");
    var clientId = ConfigurationManager.AppSettings["AuthNClientId"];
    var uri = ConfigurationManager.AppSettings["AuthNUri"];
    var userName = ConfigurationManager.AppSettings["AuthNUserName"];
    var password = ConfigurationManager.AppSettings["AuthNPassword"];

    var client = new WebClient();
    string formData = $"client_id={clientId}&grant_type=password&username={userName}&password={password}";
    client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    var response = client.UploadString($"{uri}", formData);
    dynamic authResult = JsonConvert.DeserializeObject(response);
    _accessToken = authResult.access_token;
    if (_accessToken == null)
    {
        throw new ApplicationException("Unable to authenticate. Check your configuration file <appSettings>.");
    }
    Console.WriteLine("Authenticated.");
}

另一方面,此代码 returns 一个 BadRequest 响应代码。

static async Task<string> GetAuthenticationToken()
{
    string token = string.Empty;

    var clientId = ConfigurationManager.AppSettings["AuthNClientId"];
    var uri = ConfigurationManager.AppSettings["AuthNUri"];
    var userName = ConfigurationManager.AppSettings["AuthNUserName"];
    var password = ConfigurationManager.AppSettings["AuthNPassword"];

    client.BaseAddress = new Uri("https://myurl.com/oauth2/token");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded");

    var path = $"client_id={clientId}&grant_type=password&username={userName}&password={password}";
    HttpResponseMessage response = await client.GetAsync($"https://myurl.com/oauth2/token?{path}");
    if (response.IsSuccessStatusCode)
    {
        Console.WriteLine("success");
        token = await response.Content.ReadAsStringAsync();
    }
    else { Console.WriteLine($"failure: {response.StatusCode}"); }
    return token;
}

您可以看到我已经尝试了几种方法,包括设置客户端 BaseAddress 以及尝试将 url 传递给 GetAsync 方法。

有人看到我做错了什么了吗?

UploadString 是第一个示例中的 POST 方法。在第二个示例中,正在执行 GET 方法。

static async Task<string> GetAuthenticationTokenAsync() {
    string token = string.Empty;

    var clientId = ConfigurationManager.AppSettings["AuthNClientId"];
    var uri = ConfigurationManager.AppSettings["AuthNUri"];
    var userName = ConfigurationManager.AppSettings["AuthNUserName"];
    var password = ConfigurationManager.AppSettings["AuthNPassword"];

    var client = new HttpClient();
    client.BaseAddress = new Uri(uri);
    client.DefaultRequestHeaders.Accept.Clear();

    var nameValueCollection = new Distionary<string, string>() {
        { "client_id", clientId },
        { "grant_type", "password" },
        { "username", userName },
        { "password", password },
    };
    var content = new FormUrlEncodedContent(nameValueCollection);
    var response = await client.PostAsync("", content);
    if (response.IsSuccessStatusCode) {
        Console.WriteLine("success");
        var json = await response.Content.ReadAsStringAsync();
        dynamic authResult = JsonConvert.DeserializeObject(json);
        token = authResult.access_token;
    }
    else { Console.WriteLine($"failure: {response.StatusCode}"); }
    return token;
}