Overload controllers

Is it possible to call same url with different parameters in c#? If I do this for example it will lead to an AmbiguousActionException

    [HttpPost("SetDog")]
    public async Task<bool> SetDog([FromBody] Affenpinscher affenpinscher)
    {
        ...
    }

    [HttpPost("SetDog")]
    public async Task<bool> SetDog([FromBody] Bulldog bulldog)
    {
        ...
    }

I Know that I can change the names of the controller but this is not an option. The URL needs to be the same for all request but the unique change will be the received parameters.

The url will be www.foo.com/Dogs/SetDog for all requests

P.S: Don't focus on dog example cause is just to explain the issue

2 answers

  • answered 2018-07-12 07:51 Davesoft

    Nope. You can achieve something similar by letting that URL accept Object, then analysing it to guess which type it is. But .net style type-overloading can't be done with these controllers, since the input is not truly strongly typed.

  • answered 2018-07-12 08:15 IteratioN7T

    Define an action selector for MVC to know which action method is to be triggered

    [RouteDogToAction("affenpinscher")]
    public async Task<bool> SetDog([FromBody] Affenpinscher affenpinscher)
    { 
        //Implementation 
    }
    
    [RouteDogToAction("bulldog")]
    public async Task<bool> SetDog([FromBody] Bulldog bulldog) 
    { 
        //Implementation
    }
    

    Override the ActionMethodSelectorAttribute class

    public class RouteDogToActionAttribute : ActionMethodSelectorAttribute 
    {
    
        public RequireRequestValueAttribute(string dogType) 
        {
            DogType = dogType;
        }
        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) 
        {
            return (controllerContext.HttpContext.Request[DogType] != null);
        }
    
        public string DogType { get; private set; }
    
    }