Search code examples
c#asp.netasp.net-web-apiasp.net-web-api2attributerouting

Conditionally invoke action methods with same URL and Http Verb


I would like to create 2 action methods with same URL and Http Verb but conditionally invoke only one of them to the Web API framework based on a boolean flag. What would be the best way to achieve this?

    [HttpPost]
    [Route("api/data/{id}")]
    public HttpResponseMessage PostV1(long id, RequestDTO1 v1) {

    }


   [HttpPost]
   [Route("api/data/{id}")]
   public HttpResponseMessage PostV2(long id, RequestDTO2 v2) {

   }

Either PostV1 or PostV2 should be invoked based on a boolean flag at runtime. The boolean flag will either be a feature flag or a config flag. I cannot update the URLs to contain the flag. That is not under my control.


Solution

  • If the version is governed by a config switch that is read at startup time, you can remove the RouteAttribute from your action methods and instead define the routing in your global.asax.cs or App_Start\RouteConfig.cs (or whatever it is your site uses). Use a simple if condition to define a different routing under different circumstances.

    if (configSwitch)
    {
        routes.MapRoute(
            "Custom",
            "api/data/{id}",
             new { 
                     controller = "MyController", 
                     action = "PostV1"
                 }
        );
    }
    else
    {
        routes.MapRoute(
            "Custom",
            "api/data/{id}",
             new { 
                     controller = "MyController", 
                     action = "PostV2"  //Notice the version difference
                 }
        );
    }
    

    Or (slightly shorter):

    routes.MapRoute(
        "Custom",
        "api/data/{id}",
         new { 
                 controller = "MyController", 
                 action = configSwitch ? "PostV1" : "PostV2"
             }
    );
    

    See this knowledge base article for more information.