远程服务器返回错误:(401)未经授权

时间:2011-11-20 13:52:52

标签: c# asp.net .net

我写了这段代码:

string _response = null;
string _auth = "Basic";
Uri _uri = new Uri("http://my.domain.local/my-page.aspx");
HttpWebRequest _req = (System.Net.HttpWebRequest)WebRequest.Create("http://api.olr.com/Service.svc");
CredentialCache _cc = new CredentialCache();
HttpWebResponse _res = default(HttpWebResponse);
StreamReader _sr = default(StreamReader);

_cc.Add(_uri, _auth, new NetworkCredential("username", "password", "ttp://api.olr.com/Service.svc"));
_req.PreAuthenticate = true;
_req.Credentials = _cc.GetCredential(_uri, _auth);
var response = _req.GetResponse();

System.IO.StreamReader sr =
                new System.IO.StreamReader(_res.GetResponseStream());

//_sr = new StreamReader(_res.GetResponseStream);
_response = _sr.ReadToEnd();
_sr.Close();

但得到:

  

远程服务器返回错误:(401)未经授权。

var response = _req.GetResponse();

2 个答案:

答案 0 :(得分:1)

你错过了“http://api.olr.com/Service.svc”中的'h'

 _cc.Add(_uri, _auth, new NetworkCredential("username", "password", "ttp://api.olr.com/Service.svc"));

并设置WebProxy

System.Net.WebProxy proxy = new WebProxy("http://api.olr.com", true);
proxy.Credentials = new NetworkCredential("platinum", "01CFE4BF-11BA", "http://api.olr.com/Service.svc");
_req.Proxy = proxy;

答案 1 :(得分:0)

我认为您的NetworkCredential没有正确构建。根据{{​​3}},第三个属性是域,但您传递的是完整的URL。您需要从第三方了解正确的域名是什么。

与此同时,您可以尝试将该属性保留,以查看登录是否成功。