Search code examples
asp.netasp.net-mvcasp.net-web-apiasp.net-web-api-routing

Web.Api routing additional parameters to route


How can I add additional parameters to web api route? I want to add one parameter to default route and support versioning my api, sth like this: api/{version}/{controller}/{action}/{id}

I know that {controller} is mapped automatically with controller name and {action} metho name, but what or how could to {version} mapped?

p.s. yeah, sound very weird question, but...


Solution

  • In your WebApiConfig.cs , you need to have -

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{version}/{controller}/{action}/{id}",
                defaults: new { version = 1, id = RouteParameter.Optional }
            );
    

    And when you execute the values controler getjson action -

        public string GetJson(string id)
        {
            return "me";
        }
    

    You get following output -

    enter image description here

    If you want to version your WebAPI endpoints, then use this namespaces approach. Alternatively, you can also use Http header approach. Or else simply route approach.