Versioning Web API actions in ASP.NET MVC 4

前端 未结 5 1348
小蘑菇
小蘑菇 2021-02-01 09:56

I have an ASP.NET MVC 4 app. I want to use the new Web API feature for learning purposes. I want to learn how to expose the same endpoint, but provide different versions of it.

5条回答
  •  醉话见心
    2021-02-01 10:51

    You're probably running into issues because the controllers have the same name. The controller namespace or the folder it's in doesn't matter at all to WebAPI, only the name does. The simplest thing I can think of is to rename your controllers ProductsV1Controller and ProductsV2Controller and set up two routes to point to your controllers:

    config.Routes.MapHttpRoute(
        name: "1-0Api",
        routeTemplate: "api/1.0/Products/{id}",
        defaults: new { controller = "ProductsV1", id = RouteParameter.Optional }
    );
    config.Routes.MapHttpRoute(
        name: "2-0Api",
        routeTemplate: "api/2.0/Products/{id}",
        defaults: new { controller = "ProductsV2", id = RouteParameter.Optional }
    );
    

    Of course, this gets messy if you have multiple controllers you want to expose in this way. Let me see if I can't think of something better for you.

提交回复
热议问题