我有一個使用HttpClient的異步方法:從HttpClient的更改爲Web客戶端,發送密碼以純文本
private static HttpClient client = new HttpClient(); //As pointed by @maccettura
private async Task<string> GetResult(Uri url, string user, string pass)
{
var PassArray = new UTF8Encoding().GetBytes(user + ":" + pass);
client.BaseAddress = url;
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(_passArray));
string result;
using (HttpResponseMessage response = await client.GetAsync(url))
using (HttpContent content = response.Content)
{
result = await content.ReadAsStringAsync();
}
return result;
}
,我不得不改變,以同步的WebClient
private string GetResult(Uri url, string user, string pass)
{
using (var client = new WebClient())
{
client.UseDefaultCredentials = true;
client.Credentials = new NetworkCredential(user, pass);
using (var stream = client.OpenRead(url))
using (var streamReader = new StreamReader(stream, Encoding.UTF8, true))
{
return streamReader.ReadToEnd();
}
}
}
我是不是通過犧牲安全性發送普通用戶名和密碼?如果是這樣,有沒有辦法提高安全性? (該網址是一個https地址)
僅供參考,[您正在使用HttpClient錯誤](https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/)。 – maccettura
@maccettura Oooo ...有趣。謝謝! – Yasskier
這是使用HTTPS,而不是您使用的保護憑據的庫。無論如何,Base64編碼不是任何保護。 – Crowcoder