我需要任何知道C#的人的帮助!我需要创建一个简单的C#脚本来创建Web请求,并且能够使用HTTP身份验证登录。我正在我的一个网站上测试我设置了密码锁的脚本(不要担心没有任何机密,只是密码被阻止用于测试目的): www.alienauthoritythegame.com
用户名和密码:edward tester
我已经找到了几个关于如何执行此操作的解决方案(包括此处的StackOverflow),但它们都不起作用。我尝试的每个代码/方法都包含了我尝试的方法上面的注释。这些都不起作用。当我试图从网页上得到回复时,我每次都得到401。任何帮助表示赞赏。
http_username = "edward";
http_password = "tester";
http_authentication = 1;
try
{
string url = "http://alienauthoritythegame.com";
Uri myUri = new Uri(url);
WebRequest request = HttpWebRequest.Create(myUri);
HttpWebRequest myHttpWebRequest = (HttpWebRequest)request;
request.PreAuthenticate = true;
// Set up the credentials
if (http_authentication == 1)
{
// method 1: Doesn't work
NetworkCredential myNetworkCredential = new NetworkCredential(http_username, http_password);
CredentialCache myCredentialCache = new CredentialCache();
myCredentialCache.Add(myUri, "Basic", myNetworkCredential);
request.PreAuthenticate = true;
request.Credentials = myCredentialCache;
// Method 2: doesn't work
ICredentials credentials = new NetworkCredential( "edward", "tester", "http://alienauthoritythegame.com"); //I used my username and password here
request.Credentials = credentials;
// Method 3: doesn't work
System.Net.NetworkCredential netCredential = new System.Net.NetworkCredential("edward", "tester", "http://alienauthoritythegame.com");
request.Credentials = netCredential;
// Method 4: doesn't work
string authInfo = http_username + ":" + http_password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
// Method 5: doesn't work
byte[] credentialBuffer = new UTF8Encoding().GetBytes("edward" + ":" + "tester");
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(credentialBuffer);
}
// Creates a 401 every time
WebResponse response = request.GetResponse();
}
catch (Exception webEx)
{
Response.Write(webEx.ToString());
}