独立类无法模拟为登录的用户

本文关键字:登录 用户 模拟 独立 | 更新日期: 2023-09-27 18:18:35

我有一个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服务器并执行命令的代码。问题是,我无法使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();
        });
    }

独立类无法模拟为登录的用户

您需要将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();
    }
});