我有一个名为scope的对象,该对象使我可以连接到服务器。我想在整个过程中保留该对象,因此需要将其传递给另一个控制器。这是连接到服务器控制器:
public IActionResult Proceed(Server serverModel)
{
if (!ModelState.IsValid) return View("Connect");
else
{
try
{
// --------- This is what I need to save ------------ \\
ManagementScope scope = Connecting.ConnectToServer(serverModel);
// --------- This is what I need to save ------------ \\
return RedirectToAction("Menu", "Schema");
}
catch (Exception e)
{
ViewBag.Message = e.Message.ToString();
return View("Failed");
}
}
}
在另一个控制器中,我需要将其作为参数传递:
public IActionResult ExportProceed(SchemaExport ex)
{
if (!ModelState.IsValid) return View("Export");
else
{
try
{
ExportProcess.CreateDirectories(ex, scope);
return RedirectToAction("Menu", "Schema");
}
catch (Exception e)
{
ViewBag.Message = e.Message.ToString();
return View("Failed");
}
}
}
我通常不提倡创建单例,但如此处所述,它们有时会很有用。由于您没有使用DI,这可能是一个很好的用例。
例如,如果使您的ConnectToServer
类静态?
public static class Connecting
{
private static ManagementScope scope;
public static void SetScope(Server sv)
{
// WMI scope
ConnectionOptions options = new ConnectionOptions
{
Username = sv.User,
Password = sv.Pass
};
scope = new ManagementScope(@"\\" + sv.Name + @"\root\cimv2", options);
scope.Connect();
}
public static ManagementScope GetScope { get { return scope; } }
}
然后在您的Proceed
操作中:
// ---------- This is the function returning the scope ---------- \\
Connecting.SetScope(serverModel);
// ---------- This is the function returning the scope ---------- \\
在您的ExportProceed
行动中:
// ---------- This is where i need to pass the scope ---------- \\
var scope = Connecting.GetScope;
ExportProcess.CreateDirectories(ex, scope);
// ---------- This is where i need to pass the scope ---------- \\
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句