Web API versioning configuration

后端 未结 2 365
我在风中等你
我在风中等你 2021-01-07 09:27

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,

2条回答
  •  不思量自难忘°
    2021-01-07 10:11

    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(routeData, "version");
    versionName = versionName ?? DefaultVersion;
    

提交回复
热议问题