2015-10-19 66 views
0

我有一个C#worker类(不是ASPX页面的一部分),它执行一些SQL连接。该类本身是静态的,并由ASMX Web服务实例化。独立类无法以登录用户模拟

[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.Web.Script.Services.ScriptService] 
public class AjaxServices : System.Web.Services.WebService 
{ 
    /// <summary> 
    /// This calls the worker class for the long-running process. 
    /// </summary> 
    static RunCreatorClient workProcessor = new RunCreatorClient(); 

    [WebMethod] 
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)] 
    public String StartProcess(DateTime date, string name) //starts the process 

在worker类中,我有连接到SQL Server并执行命令的代码。问题是,我无法使SYSTEM_USER等于登录用户。它始终连接到SQL作为执行机器名称。

using System.Security.Principal; 
using (WindowsIdentity.GetCurrent().Impersonate()) 
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString())) 
{ 

此方法StartProcessing()开始SQL作业。

/// <summary> 
/// Worker class that executes a long-running process. 
/// </summary> 
public class RunCreatorClient 
{ 
    /// <summary> 
    /// Non-blocking call that starts running the long-running process. 
    /// </summary> 
    public void StartProcessing() 
    { 
     // Reset the properties that report status. 
     IsComplete = false; 
     IsRunning = true; 
     PercentComplete = 0; 

     // Kick off the actual, private long-running process in a new Task 
     task = Task.Factory.StartNew(() => 
     { 
      CommitToDb(); 
     }); 
    } 

回答

1

您需要将CommitToDb()放在模拟的上下文中。

using System.Security.Principal; 
WindowsIdentity impersonatedUser = WindowsIdentity.GetCurrent(); 

// Kick off the actual, private long-running process in a new Task 
task = Task.Factory.StartNew(() => 
{ 
    using(WindowsImpersonationContext ctx = impersonatedUser.Impersonate()) 
    { 
     CommitToDb(); 
    } 
});