有两种方法可以做到这一点,因为服务器处理身份验证的方式不同。首先你可以使用这样的东西:
var req = WebRequest.Create(<your url>);
NetworkCredential creds = new NetworkCredential(<username>, <password>);
req.Credentials = creds;
var rep = req.GetResponse();
但是,如果您需要一个实际的授权标头,您将需要使用此代码
public void SetBasicAuthHeader(WebRequest req, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
req.Headers["Authorization"] = "Basic " + authInfo;
}
然后您的请求代码变为
var req = WebRequest.Create(<your url>);
SetBasicAuthHeader(req, username, password);
rep = req.GetResponse();
如果您有任何问题,请告诉我。