3

我想在 ASP.NET MVC 的不同控制器中声明 API 的多个版本。有可能做这样的事情吗?

routes.MapRoute(
    "Default", // Route name
    "API/{version}/{action}/{id}", 
        new { 
             controller = "APIv{version}", 
             action = "Index", 
             id = UrlParameter.Optional 
        } 
    );

或者

routes.MapRoute(
    "Default", // Route name
    "API/{version}/{action}/{id}", 
        new { 
             controller = "APIv" + version, 
             action = "Index", 
             id = UrlParameter.Optional 
        } 
    );
4

1 回答 1

4

我通过将不同的 api 版本移动到不同的区域来实现它

版本1:

 public class AreaRegistration : PortableAreaRegistration
    {
        public override string AreaName
        {
            get { return "Api.v1"; }
        }

        public override void RegisterArea(System.Web.Mvc.AreaRegistrationContext context)
        {
            context.MapHttpRoute(
                    name: "Api.v1_Default",
                    routeTemplate: "api/v1/{company}/{action}",
                    defaults: new { controller = "Company", action = "Employees" }
            );
        }
    }

版本 1.1:

  public class AreaRegistration : PortableAreaRegistration
        {
            public override string AreaName
            {
                get { return "Api.v1.1"; }
            }

            public override void RegisterArea(System.Web.Mvc.AreaRegistrationContext context)
            {
                context.MapHttpRoute(
                        name: "Api.v1_1_Default",
                        routeTemplate: "api/v1.1/{company}/{action}",
                        defaults: new { controller = "Company", action = "Employees" }
                );
            }
        }

请注意使用了来自 MvcContrib 的 PortableAreaRegistration。

于 2013-04-12T15:51:52.757 回答