我有一个名为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");
}
}
}
答案 0 :(得分:0)
您可以使用TempData["YourName"] = JsonConvert.SerializeObject(Connecting.ConnectToServer(serverModel));
那么您会返回RedirectToAction("Menu", "Schema");
。
之后,您只需在Controller菜单中从TempData中获取此数据即可。
var scope = JsonConvert.DeserializeObject<ManagementScope>((string)TempData["YourName"]);
记住TempData仅存在两个请求
答案 1 :(得分:0)
我通常不提倡创建单例,但正如here所述,它们有时会很有用。由于您不使用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 ---------- \\