0

我需要创建一个 Windows 应用程序,它将访问 SharePoint 2010 网站页面,以便在本地驱动器中以“.htm”格式存储该页面。

但是,该 SharePoint 网站具有基于声明的身份验证。

为了访问该站点,我必须提供“用户名”和“密码”以及“域名”。

因此,我需要有关如何通过 Windows 应用程序传递站点凭据以访问该站点的帮助?

我使用了以下代码,但这会引发异常“远程服务器返回错误:(403)禁止”。

WebRequest Request1;
HttpWebResponse Response1;

Request1 = WebRequest.Create(txtUrl.Text.ToString());
Request1.Credentials = new NetworkCredential(strUserNm.ToString(), strPassword.ToString(), StrDomain.ToString());

Request1.PreAuthenticate = true;
Response1 = (HttpWebResponse)Request1.GetResponse();

任何帮助都将是可观的......

4

2 回答 2

1

基于具有双重身份验证模式的预热计时器作业,我对此进行了更改:

WebRequest request = WebRequest.Create(url);
request.Method = "GET";
request.Timeout = System.Threading.Timeout.Infinite;
request.Credentials = CredentialCache.DefaultNetworkCredentials;
WebResponse response = request.GetResponse();

对此:

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.Timeout = System.Threading.Timeout.Infinite;
request.Credentials = new CredentialCache
{
    { new Uri(url), "NTLM", new NetworkCredential(username, password, domain) }
};
request.Headers.Add("Authorization", GetAuthorization(username, password, domain));
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-TW; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 GTB7.1 ( .NET CLR 3.5.30729)";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.CookieContainer = new CookieContainer();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;

GetAuthorization 方法如下所示:

private function GetAuthorization(string username, string password, string domain) 
{
    string credentials = string.Format(@"{0}\{1}:{2}", domain, username, password);
    byte[] bytes = Encoding.ASCII.GetBytes(credentials);
    string base64 = Convert.ToBase64String(bytes);
    return = string.Concat("NTLM ", base64);
}

使用更新后的代码,我能够访问 Classic 和 Claims Based web 应用程序中的文件。

于 2014-01-15T20:32:22.147 回答
0

注意域是如何被捕获的。

//不要使用域\用户名或用户名@域作为此构造函数的用户名参数。这将不起作用(按设计)。接受域的构造函数有 3 个参数。或者使用上面示例代码中明确记录的域属性。

// Call the onstructor  to create an instance of NetworkCredential with the 
// specified user name and password.

NetworkCredential myCredentials = new NetworkCredential(username,passwd);

// Create a WebRequest with the specified URL. 
WebRequest myWebRequest = WebRequest.Create(url);
myCredentials.Domain = domain;
myWebRequest.Credentials = myCredentials;
Console.WriteLine("\n\nCredentials Domain : {0} , UserName : {1} , Password : {2}",
myCredentials.Domain, myCredentials.UserName, myCredentials.Password);
Console.WriteLine("\n\nRequest to Url is sent.Waiting for response...");


// Send the request and wait for a response.
WebResponse myWebResponse = myWebRequest.GetResponse(); 

// Process the response.
Console.WriteLine("\nResponse received successfully.");
// Release the resources of the response object.
myWebResponse.Close();
于 2012-08-03T18:26:41.017 回答