I new in Mvc and try to write restful api, I use web api type of application, and try to create versioning, In final I would like to have link type like api/v1/values/get,
API versioning through namespace is explained here. Create a new HttpControllerSelector for yourself as described in the blog post and given example, then switch to that selector in your FilterConfig
via:
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(GlobalConfiguration.Configuration));
Then, register your routes:
config.Routes.MapHttpRoute(
name: "VersionedApi",
routeTemplate: "api/{version}/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
In your custom HttpControllerSelector
, if you want to fallback to a default version, then use the following:
string versionName = GetRouteVariable<string>(routeData, "version");
versionName = versionName ?? DefaultVersion;
You can use attribute routing to achieve this kind of versioning. For your example it would look similar to the code snippet below
[RoutePrefix("api/v1/values")]
public class ValuesController : ApiController
{
public object Get(int id) { ... }
}
[RoutePrefix("api/v2/values")]
public class NewValuesController : ApiController
{
public object Get(int id) { ... }
}
Edit
Don't forget to enable attribute routing if you have an existing project. Your WebApiConfig should contain the following snippet:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
You can delete the MapHttpRoute part if you don't want to use the convention-based configuration.
You should also make sure that your Global.asax contains the following:
protected void Application_Start()
{
// Pass a delegate to the Configure method.
GlobalConfiguration.Configure(WebApiConfig.Register);
}