如何调用Task.WaitAll()时,我设置任务的用户身份? [英] How do I set the user identity for tasks when calling Task.WaitAll()?

查看:167
本文介绍了如何调用Task.WaitAll()时,我设置任务的用户身份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有并行调用WCF服务的问题。我试图使用任务并行调用两个服务,以节省一些时间(我并不想使这个异步),但我的任务正在运行的另一个用户。这两种服务都需要Windows认证和两个呼叫失败,因为用户调用该服务不具备所需的权限。

I'm having a problem invoking WCF services in parallel. I'm trying to use Tasks to invoke two services in parallel to save some time (I'm NOT trying to make this async), but my tasks are being run as another user. Both services require Windows authentication and both calls fail because the user invoking the service does not have the required permissions.

调用代码(代码如下所示)位于一个控制器的动作里面在ASP.NET MVC4,运行IIS 7.5。所有涉及的应用程序池设置为允许ASP.NET模拟,并要求Windows身份验证(所有其他方法设置为禁用)。

The calling code (code below) is located inside a Controller Action in ASP.NET MVC4, running IIS 7.5. All application pools involved are set to allow ASP.NET Impersonation and require Windows Authentication (all other methods set to disabled).

// Parallel service request to two services
Task<object>[] tasks = new Task<object>[2];

// this shows my credentials, e.g. "MYDOMAIN\\MyUsername"
var userMe = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

tasks[0] = Task<object>.Factory.StartNew(() => 
{
    // this shows "IIS APPPOOL\\DefaultAppPool"
    var user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

    var data = client1.MyMethod();
    return data;
});

tasks[1] = Task<object>.Factory.StartNew(() =>
{
    // this shows "IIS APPPOOL\\DefaultAppPool"
    var user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

    var data = client2.MyMethod();
    return data;
});

Task.WaitAll(tasks);

我的问题:我如何指导,而不是为当前用户运行的任务,作为运行IIS APPPOOL\DefaultAppPool用户

推荐答案

试试这个:

WindowsIdentity impersonatedUser = WindowsIdentity.GetCurrent();

Task<object>.Factory.StartNew(() =>
{
    using (WindowsImpersonationContext ctx = impersonatedUser.Impersonate())
    {
       //Your code
    }
    return data;
});

这篇关于如何调用Task.WaitAll()时,我设置任务的用户身份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆