2015-10-19 16 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(); 
    } 
});