Skip to main content
 首页 » 编程设计

c#之Windows 窗体调用 Web 服务但需要模拟不同的 Windows 用户

2024年02月24日36lonelyxmas

我有一个调用 Web 服务 (WCF) 的 Windows 窗体应用程序 (4.0),但需要模拟与当前登录计算机的用户不同的用户。那怎么办?现在 Web 服务无法返回记录,因为用户没有权限。我需要为 Web 服务调用使用不同的用户。

请您参考如下方法:

从我执行此操作的应用中:

NetworkCredential credentials = new NetworkCredential(user, pw, userDomain); 
 
//  This is the client generated by the WCF Service Reference 
AppClient appClient = new AppClient(); 
 
appClient.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation; 
appClient.ClientCredentials.Windows.ClientCredential = credentials; 
 
appClient.MyWcfServiceCall(); 

现在将根据提供的凭据完成对 WCF 服务的调用。您的 WCF 服务方法必须经过修饰以允许模拟:

[OperationBehavior(Impersonation = ImpersonationOption.Allowed)] 

或

[OperationBehavior(Impersonation = ImpersonationOption.Required)] 

根据您的需要。

在 WCF 服务中,您有以下有关登录用户的信息:

OperationContext.Current.ServiceSecurityContext 
Thread.CurrentPrincipal.IsInRole(roleName) 
Thread.CurrentPrincipal.Identity 

您还可以查看 LogonUser() 以了解其他模拟方法:http://msdn.microsoft.com/en-us/library/ff647404.aspx#paght000023_impersonatingusinglogonuser

喂! 詹姆斯