Web API versioning configuration

后端 未结 2 364
我在风中等你
我在风中等你 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<string>(routeData, "version");
    versionName = versionName ?? DefaultVersion;
    
    0 讨论(0)
  • 2021-01-07 10:27

    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);
    }
    
    0 讨论(0)
提交回复
热议问题