我正在使用WebClient
而不是HttpClient
来从MVC控制器进行一些WebAPI调用。但是,我一直收到401 Unauthorized
错误。在以下代码中,我使用WebClient
初始化UseDefaultCredentials = true
。我仍然得到错误。
_lazyClient = new Lazy<WebClient> (() => new WebClient {
UseDefaultCredentials = true
});
public static class WebClientWrapper
{
static private string _baseUrl;
static private Lazy<WebClient> _lazyClient;
static private WebClient Client()
{
if (_lazyClient == null)
{
throw new ObjectDisposedException("WebClient has been disposed");
}
//string myUri = _baseUrl;
//CredentialCache cc = new CredentialCache();
//cc.Add(new Uri(myUri), "NTLM", CredentialCache.DefaultNetworkCredentials);
//_lazyClient.Value.Credentials = cc;
return _lazyClient.Value;
}
static public T Execute<T> (string baseUrl, string urlSegment)
{
_baseUrl = baseUrl.Trim('/');
_lazyClient = new Lazy<WebClient> (() => new WebClient {
UseDefaultCredentials = true
});
return JsonConvert.DeserializeObject<T>(Client().DownloadString(_baseUrl + '/' + urlSegment.TrimStart('/')));
}
}