在asp.net mvc控制器中封装开关逻辑



我尝试改进以下代码。问题是Handle方法变得很麻烦。我正在寻找一种从主方法中排除加法和处理命令的方法。我希望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);
        }
    }

您的方法可以重做为以下内容:

  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

最新更新