Web API versioning configuration

后端 未结 2 391
我在风中等你
我在风中等你 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: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);
    }
    

提交回复
热议问题