以下是用於檢查SharePoint文檔庫中是否存在文件夾的2個代碼片段。 PROPFIND方法似乎工作,而另一種方法,使用HEAD結果爲401.C#Web Dav,爲什麼頭部請求會生成401?
有人可以告訴我爲什麼嗎?不要被憑據分心,我已經將它設置爲相同的在這兩個例子中,它工作正常....
這裏是工作的代碼:
// Create the web request object
var oReq = (HttpWebRequest)WebRequest.Create(url);
// Set the needed properties
oReq.Method = "PROPFIND";
oReq.Credentials = this.wsLists.Credentials; // Use same credentials as wsLists.
oReq.AllowAutoRedirect = true;
oReq.UserAgent = "Microsoft-WebDAV-MiniRedir/6.1.7600";
// Enumerate through top level only, increasing the depth will find children.
oReq.Headers["Depth"] = "0";
oReq.Headers["translate"] = "f";
var oRequest = new StreamWriter(oReq.GetRequestStream());
oRequest.WriteLine();
oRequest.Close();
var oResponse = new StreamReader(oReq.GetResponse().GetResponseStream());
string sResponse = oResponse.ReadToEnd();
oResponse.Close();
,這裏是有問題的代碼:
private bool MossResourceExists(string url)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
// Create a new CredentialCache object and fill it with the network
// credentials required to access the server.
var myCredentialCache = new CredentialCache();
if (!string.IsNullOrEmpty(this.Domain))
{
myCredentialCache.Add(new Uri(url),
"NTLM",
new NetworkCredential(this.Username , this.Password , this.Domain)
);
}
else
{
myCredentialCache.Add(new Uri(url),
"NTLM",
new NetworkCredential(this.Username , this.Password)
);
}
request.Credentials = myCredentialCache;
try
{
request.GetResponse();
return true;
}
catch (WebException ex)
{
var errorResponse = ex.Response as HttpWebResponse;
if (errorResponse != null)
if (errorResponse.StatusCode == HttpStatusCode.NotFound)
return false;
else
throw new Exception("Error checking if URL exists:" + url + ";Status Code:" + errorResponse.StatusCode + ";Error Message:" + ex.Message) ;
}
return true;
}
非常好的見解,感謝科林。 – 2010-01-07 11:23:12