1

我在应用程序中有许多控制器:

ApiV1Controller
ApiV2Controller
ApiV3Controller
...

是否可以使用单个MapRoute语句将它们的路由映射到 URL 之类的/api/v1/{action}

4

1 回答 1

1

您可以编写自定义路线。假设您有以下控制器:

public class ApiV1Controller : Controller
{
    public ActionResult Index()
    {
        return Content("v1");
    }
}

public class ApiV2Controller : Controller
{
    public ActionResult Index()
    {
        return Content("v2");
    }
}

public class ApiV3Controller : Controller
{
    public ActionResult Index()
    {
        return Content("v3");
    }
}

现在编写一个自定义路由:

public class ApiRoute : Route
{
    public ApiRoute()
        : base("api/{version}/{action}", new RouteValueDictionary(new { action = "index" }), new MvcRouteHandler())
    {
    }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var rd = base.GetRouteData(httpContext);
        if (rd == null)
        {
            return null;
        }

        rd.Values["controller"] = "Api" + rd.GetRequiredString("version");
        return rd;
    }
}

这可以在您的注册Global.asax

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.Add("ApiRoute", new ApiRoute());

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );
}

差不多就是这样。现在你可以玩 url:

  • /api/v1
  • /api/v2
  • /api/v3
于 2012-09-25T20:42:59.910 回答