我在ASP.NET核心2.1中有一个非常奇怪的问题我正在编写一个简单的Web应用程序,在需要的场景中调用Powershell脚本。模拟在C#级别上运行完美,但是一旦我调用Powershell脚本,就会使用默认标识(运行IIS Express的标识)调用它。我知道在ASP.NET中很容易通过aspnet.config文件启用跨线程模拟,但我不知道如何在ASP.NET Core中执行类似的实现。下面的代码是有问题的功能(虽然函数不是我想的问题)。
internal void InvokeScript()
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Impersonation.LogonUser(userName, domain, password, 2, 0, out
SafeAccessTokenHandle handle);
WindowsIdentity.RunImpersonated(handle, () => {
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
//Setting needed variables
Collection<PSObject> PreFixOutput = new Collection<PSObject>();
Collection<PSObject> FixOutput = new Collection<PSObject>();
Collection<PSObject> PostFixOutput = new Collection<PSObject>();
// Setting directory to needed KB subdir and finding needed stage files
string KBtoWorkWith = RepositoryLocation + @"\" + KB.Number;
Directory.SetCurrentDirectory(KBtoWorkWith);
// Reading scripts from .ps1 and adding needed variables
string commandToRun1 = string.Format("$Computer = '{0}'; $Username = '{1}'; $KB = '{2}' ; {3}", IP, Username, KB.Number, File.ReadAllText("Pre" + KB.Number + ".ps1"));
string commandToRun2 = string.Format("$Computer = '{0}'; $Username = '{1}'; $KB = '{2}'; {3}; {4}; $success; $verbose", IP, Username, KB.Number, File.ReadAllText(KB.Number + ".ps1"), InnerFunction);
string commandToRun3 = string.Format("$Computer = '{0}'; $Username = '{1}'; $KB = '{2}' ; {3}", IP, Username, KB.Number, File.ReadAllText("Post" + KB.Number + ".ps1"));
// Invoking formed PS scripts & collecting returned data
ps.AddScript(commandToRun1);
PreFixOutput = ps.Invoke();
OutputToUser = PreFixOutput[1].BaseObject.ToString();
if (PreFixOutput[0].BaseObject.ToString() == "True")
{
IsFixApplicable = true;
if ((PreFixOutput[2].BaseObject.ToString()) != "")
{
InnerFunction = PreFixOutput[2].BaseObject.ToString();
}
else
{
InnerFunction = "";
}
FixOutput = ps.AddScript(commandToRun2).Invoke();
OutputToUser = FixOutput[1].BaseObject.ToString();
if (FixOutput[0].BaseObject.ToString() == "True")
{
PostFixOutput = ps.AddScript(commandToRun3).Invoke();
OutputToUser = PostFixOutput[1].BaseObject.ToString();
if (PostFixOutput[0].BaseObject.ToString() == "True")
{
WasFixApplied = true;
}
else
{
WasFixApplied = false;
}
}
else
{
WasFixApplied = false;
}
}
else
{
IsFixApplicable = false;
WasFixApplied = false;
}
//runspace.Close();
});
}
只为每个人都知道。我在DEV环境中从未解决过这个问题。 ASP.NET CORE上的Neithet,ASP.NET 4.5.2上也没有。这看起来是一个IIS Express问题。一旦我在我的机器上托管了功能齐全的IIS并发布我的应用程序模拟就开始工作了。