【问题标题】:Encapsulation switch logic in asp.net mvc controllerasp.net mvc控制器中的封装开关逻辑
【发布时间】:2013-11-24 17:03:20
【问题描述】:

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

        }
    }

【问题讨论】:

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


    【解决方案1】:

    您的方法可以重做如下:

      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

    【讨论】:

    • 这就是我在看的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 2017-06-03
    相关资源
    最近更新 更多