[英]How to pass credentials to httpwebrequest for accessing SharePoint Library
I'm trying to read files from a SharePoint document library using HttpWebRequest
. 我正在尝试使用
HttpWebRequest
从SharePoint文档库中读取文件。 In order to do that I have to pass some credentials. 为了做到这一点,我必须传递一些凭据。 I'm using the below request:
我正在使用以下请求:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/msexcel";
request.UserAgent = "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0";
request.Credentials = new NetworkCredential(UserName, PassWord);
Is this the correct way to pass credentials? 这是传递凭据的正确方法吗?
你也可以使用:
request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
If you need to run request as the current user from desktop application use CredentialCache.DefaultCredentials
(see on MSDN ). 如果您需要以桌面应用程序中的当前用户身份运行请求,请使用
CredentialCache.DefaultCredentials
(请参阅MSDN )。
Your code looks fine if you need to run a request from server side code or under a different user. 如果您需要从服务器端代码或其他用户下运行请求,则代码看起来很好。
Please note that you should be careful when storing passwords - consider using the SecureString
version of the constructor. 请注意,存储密码时应该小心 - 考虑使用构造函数的
SecureString
版本。
If you need to set the credentials on the fly, have a look at this source: 如果您需要动态设置凭据,请查看此来源:
http://spc3.codeplex.com/SourceControl/changeset/view/57957#1015709 http://spc3.codeplex.com/SourceControl/changeset/view/57957#1015709
private ICredentials BuildCredentials(string siteurl, string username, string password, string authtype) {
NetworkCredential cred;
if (username.Contains(@"\")) {
string domain = username.Substring(0, username.IndexOf(@"\"));
username = username.Substring(username.IndexOf(@"\") + 1);
cred = new System.Net.NetworkCredential(username, password, domain);
} else {
cred = new System.Net.NetworkCredential(username, password);
}
CredentialCache cache = new CredentialCache();
if (authtype.Contains(":")) {
authtype = authtype.Substring(authtype.IndexOf(":") + 1); //remove the TMG: prefix
}
cache.Add(new Uri(siteurl), authtype, cred);
return cache;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.