如何将用户凭据传递给webClient()

时间:2015-09-16 03:15:59

标签: asp.net-mvc

我正在使用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('/')));
    }
}

0 个答案:

没有答案