我还使用假冒:
using System.Security.Principal;
使用System.Runtime.InteropServices;
#region Constants
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;
#endregion
public WindowsImpersonationContext impersonationContext;
#region Win32 API
[DllImport("advapi32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int LogonUserA(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern int DuplicateToken(IntPtr ExistingTokenHandle, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern long CloseHandle(IntPtr handle);
#endregion
public bool Impersonate(string userName, string domain, string password)
{
try
{
bool functionReturnValue = false;
WindowsIdentity tempWindowsIdentity = default(WindowsIdentity);
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
functionReturnValue = false;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if ((impersonationContext != null))
{
functionReturnValue = true;
}
}
}
}
if (!tokenDuplicate.Equals(IntPtr.Zero))
{
CloseHandle(tokenDuplicate);
}
if (!token.Equals(IntPtr.Zero))
{
CloseHandle(token);
}
return functionReturnValue;
}
catch (Exception ex)
{
SQMSLog.WriteLogEntry(ex.Message, "SYSTEM");
return false;
}
}
public void UndoImpersonate()
{
impersonationContext.Undo();
}
调用模拟功能第一则:
//Add Miscellaneous Data Details
data.ListNameEx = Settings.Default.SPListLoader_List_Name;
//Instantiate the Web Service
SPListService.Lists lists = new SPListLoaderService.SPListService.Lists();
//Bind Appropriate Credentials to the Web Service
lists.Credentials = new NetworkCredential(data.UserName, data.Password, data.Domain);
//Set the List Object URI
lists.Url = data.URI.TrimEnd('/') + "/_vti_bin/lists.asmx";
一旦完成,你需要释放内容:
UndoImpersonate();
以上是非常重要的,一旦你有你执行什么都称为Impersonate();将在该用户凭据下运行。
希望这有助于。
干杯。
大家好,只是为了让你知道,我得到更好的结果IMEX = 0在ConnectionString(不知道为什么,因为我没有发现任何有关此参数的文档)。我希望这有帮助。问候 – 2011-05-09 16:27:39