具有基本身份validation的Webclient / HttpWebRequest返回404找不到有效的URL

编辑:我想回来注意,这个问题不是我的目的,而是与其他公司的代码。

我正在尝试使用基本身份validation拉起一个页面。 我不断收到404页未find错误。 我可以复制和粘贴我的url到浏览器,它工作正常(如果我没有login到他们的网站已经popup一个凭证框,否则它打开我想要它打开)。 我必须得到正确的地方和身份validation,因为我得到一个401(未authentication的错误),如果我暗中input一个错误的用户名/密码,我得到一个内部服务器错误500,如果我把它传递一个错误的参数在查询string。 我试过使用Webclient和HttpWebRequest都导致相同的404找不到错误。

使用Webclient:

string url = "MyValidURLwithQueryString"; WebClient client = new WebClient(); String userName = "myusername"; String passWord = "mypassword"; string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord)); client.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials; var result = client.DownloadString(url); Response.Write(result); 

与HttpWebRequest

  HttpWebRequest request = (HttpWebRequest)WebRequest.Create("MyValidURL"); string authInfo = "username:password"; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); request.Headers.Add("Authorization", "Basic " + authInfo); request.Credentials = new NetworkCredential("username", "password"); request.Method = WebRequestMethods.Http.Get; request.AllowAutoRedirect = true; request.Proxy = null; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader streamreader = new StreamReader(stream); string s = streamreader.ReadToEnd(); Response.Write(s); 
 //BEWARE //This works ONLY if the server returns 401 first //The client DOES NOT send credentials on first request //ONLY after a 401 client.Credentials = new NetworkCredential(userName, passWord); //doesnt work //So use THIS instead to send credentials RIGHT AWAY string credentials = Convert.ToBase64String( Encoding.ASCII.GetBytes(userName + ":" + password)); client.Headers[HttpRequestHeader.Authorization] = string.Format( "Basic {0}", credentials); 

尝试将Web客户端请求authentication部分更改为:

 NetworkCredential myCreds = new NetworkCredential(userName, passWord); client.Credentials = myCreds; 

然后打个电话,似乎对我来说工作得很好。

这部分代码对我来说工作得很好:

  WebRequest request = WebRequest.Create(url); request.Method = WebRequestMethods.Http.Get; NetworkCredential networkCredential = new NetworkCredential(logon, password); // logon in format "domain\username" CredentialCache myCredentialCache = new CredentialCache {{new Uri(url), "Basic", networkCredential}}; request.PreAuthenticate = true; request.Credentials = myCredentialCache; using (WebResponse response = request.GetResponse()) { Console.WriteLine(((HttpWebResponse)response).StatusDescription); using (Stream dataStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(dataStream)) { string responseFromServer = reader.ReadToEnd(); Console.WriteLine(responseFromServer); } } } 

如果它在使用浏览器时工作,然后第一次传递用户名和密码 – 那么这意味着一旦完成身份validation,浏览器的请求标头将被设置为具有所需的身份validation值,然后每次传递请求托pipe服务器。

所以,从检查请求头开始(这可以使用Web开发工具来完成),一旦你build立了头中所需的东西,那么你可以在你的HttpWebRequest头中传递这个头。

摘要式身份validation示例:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.Text.RegularExpressions; using System.Net; using System.IO; namespace NUI { public class DigestAuthFixer { private static string _host; private static string _user; private static string _password; private static string _realm; private static string _nonce; private static string _qop; private static string _cnonce; private static DateTime _cnonceDate; private static int _nc; public DigestAuthFixer(string host, string user, string password) { // TODO: Complete member initialization _host = host; _user = user; _password = password; } private string CalculateMd5Hash( string input) { var inputBytes = Encoding.ASCII.GetBytes(input); var hash = MD5.Create().ComputeHash(inputBytes); var sb = new StringBuilder(); foreach (var b in hash) sb.Append(b.ToString("x2")); return sb.ToString(); } private string GrabHeaderVar( string varName, string header) { var regHeader = new Regex(string.Format(@"{0}=""([^""]*)""", varName)); var matchHeader = regHeader.Match(header); if (matchHeader.Success) return matchHeader.Groups[1].Value; throw new ApplicationException(string.Format("Header {0} not found", varName)); } private string GetDigestHeader( string dir) { _nc = _nc + 1; var ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", _user, _realm, _password)); var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", "GET", dir)); var digestResponse = CalculateMd5Hash(string.Format("{0}:{1}:{2:00000000}:{3}:{4}:{5}", ha1, _nonce, _nc, _cnonce, _qop, ha2)); return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", " + "algorithm=MD5, response=\"{4}\", qop={5}, nc={6:00000000}, cnonce=\"{7}\"", _user, _realm, _nonce, dir, digestResponse, _qop, _nc, _cnonce); } public string GrabResponse( string dir) { var url = _host + dir; var uri = new Uri(url); var request = (HttpWebRequest)WebRequest.Create(uri); // If we've got a recent Auth header, re-use it! if (!string.IsNullOrEmpty(_cnonce) && DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0) { request.Headers.Add("Authorization", GetDigestHeader(dir)); } HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { // Try to fix a 401 exception by adding a Authorization header if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized) throw; var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"]; _realm = GrabHeaderVar("realm", wwwAuthenticateHeader); _nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader); _qop = GrabHeaderVar("qop", wwwAuthenticateHeader); _nc = 0; _cnonce = new Random().Next(123400, 9999999).ToString(); _cnonceDate = DateTime.Now; var request2 = (HttpWebRequest)WebRequest.Create(uri); request2.Headers.Add("Authorization", GetDigestHeader(dir)); response = (HttpWebResponse)request2.GetResponse(); } var reader = new StreamReader(response.GetResponseStream()); return reader.ReadToEnd(); } 

}

那么你可以这样称呼它:

 DigestAuthFixer digest = new DigestAuthFixer(domain, username, password); string strReturn = digest.GrabResponse(dir); 

如果Url是: http : //xyz.rss.com/folder/rss那么域名: http : //xyz.rss.com (域名部分)dir:/文件夹/ rss(其余的url)

你也可以将它作为stream返回并使用XmlDocument的Load()方法。