gpt4 book ai didi

c# - asp.net mvc Controller 中封装开关逻辑

转载 作者:太空宇宙 更新时间:2023-11-03 10:53:58 28 4
gpt4 key购买 nike

我尝试改进以下代码。问题是 Handle 方法变得繁琐。我正在寻找一种方法来从 main 方法中排除添加和处理命令。我想通过添加新命令使 ActionResult HandleCommand 方法对更改关闭。所以,我对大型开关 block 并不感到兴奋。我很乐意收到任何建议。

    [HttpPost]
public ActionResult HandleCommand(string command)
{
switch (command)
{
case "foo":
DoSomthing();
return View("someView1");

case "bar":
DoSomthingElse();
return RedirectToAction("someAction");

case "fooBar":
return File("file.txt", "application");
//...

default:
//...
return new HttpStatusCodeResult(404);

}
}

最佳答案

您的方法可以重做如下:

  public ActionResult HandleCommand(string comand)
{
CommandAction Comand = commandHandler[comand] ?? new CommandAction(method, new HttpStatusCodeResult(404));
Comand.DoSomthing();
return Comand.Result;
}

如果你做了一些改变:

 public class CommandAction
{
public Action DoSomthing { get; set; }
public ActionResult Result { get; set; }

public CommandAction(Action action, ActionResult actionResult)
{
DoSomthing = action;
Result = actionResult;
}
}


public class SomeController : Controller
{
public Dictionary<string, CommandAction> commandHandler
{
get
{
return new Dictionary<string, CommandAction>()
{
{"foo", new CommandAction( DoSomthing, View("foo"))},
{"foo", new CommandAction( DoSomthingElse, RedirectToAction("someAction"))},
{"fooBar", new CommandAction( SomeMethod, File("file.txt", "application"))}
};
}

}

并且,当你添加新命令时修改commandHandler

关于c# - asp.net mvc Controller 中封装开关逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20177275/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com