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

时间:2013-11-24 17:03:21

标签: c# asp.net-mvc refactoring switch-statement

我尝试改进以下代码。问题是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);

        }
    }

1 个答案:

答案 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