我尝试改进以下代码。问题是Handle方法变得麻烦。我正在寻找一种方法来从main方法中排除添加和处理命令。我想通过添加新命令使ActionResult HandleCommand
方法变得封闭。所以,我对一个大的开关块并不感到兴奋。我很乐意收到任何建议。
[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);
}
}
答案 0 :(得分:2)
您的方法可以重做以下内容:
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
时