独立类无法模拟登录用户

时间:2015-10-19 21:49:15

标签: c# sql-server

我有一个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 个答案:

答案 0 :(得分: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();
    }
});