如果您的 SharePoint WebServices Web 应用程序使用 NTLM 身份验证,您可以试试这个
ug.ClientCredentials.Windows.ClientCredential = new NetworkCredential("myusername", "mypassword");
在你的app.config
<security mode="Transport">
<transport clientCredentialType="Ntlm" proxyCredentialType="None" realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
编辑:
由于在您的 Web 应用程序中禁用 NTLM 身份验证以访问 Web 服务,您必须首先使用 Authentication.asmx Web 服务登录并检索身份验证 cookie 并将其与其他 Web 服务调用一起发送,如下所示:
string cookie = "";
LoginResult loginResult;
string result;
AuthenticationSoapClient authentication = new AuthenticationSoapClient();
UserGroupSoapClient ug = new UserGroupSoapClient();
using(OperationContextScope scope = new OperationContextScope(authentication.InnerChannel))
{
loginResult = authentication.Login("user", "pass");
if (loginResult.ErrorCode == LoginErrorCode.NoError)
{
MessageProperties props = OperationContext.Current.IncomingMessageProperties;
HttpResponseMessageProperty prop = props[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
string cookies = prop.Headers["Set-Cookie"];
// You must search cookies to find cookie named loginResult.CookieName and set its value to cookie variable;
cookie = cookies.Split(';').SingleOrDefault(c => c.StartsWith(loginResult.CookieName));
}
}
HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers.Add(System.Net.HttpRequestHeader.Cookie, cookie);
using (new OperationContextScope(ug.InnerChannel))
{
OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequestProperty);
result = ug.GetGroupCollectionFromUser(LoginName).ToString();
}
并确保 app.config 中所有绑定的 allowCookies 属性为 false。
<basicHttpBinding>
<binding name="AuthenticationSoap" allowCookies="false"/>
<binding name="UserGroupSoap" allowCookies="false"/>
</basicHttpBinding>