Can you overload controller methods in ASP.NET MVC?

前端 未结 17 2016
无人共我
无人共我 2020-11-22 08:10

I\'m curious to see if you can overload controller methods in ASP.NET MVC. Whenever I try, I get the error below. The two methods accept different arguments. Is this some

17条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 08:45

    There is only one public signature allowed for each controller method. If you try to overload it, it will compile, but you're getting the run-time error you've experienced.

    If you're not willing to use different verbs (like the [HttpGet] and [HttpPost] attributes) to differentiate overloaded methods (which will work), or change the routing, then what remains is that you can either provide another method with a different name, or you can dispatch inside of the existing method. Here's how I did it:

    I once came into a situation where I had to maintain backwards compatibility. The original method expected two parameters, but the new one had only one. Overloading the way I expected did not work because MVC didn't find the entry point any more.

    To solve that, I did the following:

    1. Changed the 2 overloaded action methods from public to private
    2. Created one new public method which contained "just" 2 string parameters. That one acted as a dispatcher, i.e.:

      public ActionResult DoSomething(string param1, string param2)
      {
          if (string.IsNullOrEmpty(param2))
          {
              return DoSomething(ProductName: param1);
          }
          else
          {
              int oldId = int.Parse(param1);
              return DoSomething(OldParam: param1, OldId: oldId);
          }
      }
      
      
      private ActionResult DoSomething(string OldParam, int OldId)
      {
          // some code here
          return Json(result);
      }
      
      
      private ActionResult DoSomething(string ProductName)
      {
          // some code here
          return Json(result);
      }
      

    Of course, this is a hack and should be refactored later. But for the time being, it worked for me.

    You can also create a dispatcher like:

    public ActionResult DoSomething(string action, string param1, string param2)
    {
        switch (action)
        {
            case "update":
                return UpdateAction(param1, param2);
            case "remove":
                return DeleteAction(param1);
        }
    }
    

    You can see, that UpdateAction needs 2 parameters, while DeleteAction just needs one.

提交回复
热议问题