使用url值作为路由值中的变量

时间:2013-04-12 15:38:34

标签: asp.net-mvc asp.net-mvc-3 api asp.net-mvc-routing

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

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

OR

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

1 个答案:

答案 0 :(得分: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" }
            );
        }
    }

Version1.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。