假設你有如下控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
你可以寫一個自定義的路由處理:
public class MyRouteHander : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var rd = requestContext.RouteData;
var action = rd.GetRequiredString("action");
var controller = rd.GetRequiredString("controller");
if (string.Equals(action, "users", StringComparison.OrdinalIgnoreCase) &&
string.Equals(controller, "home", StringComparison.OrdinalIgnoreCase))
{
// The action name is dynamic
string actionName = "Index";
requestContext.RouteData.Values["action"] = actionName;
}
return new MvcHandler(requestContext);
}
}
最後,在你的路由定義的自定義路由處理程序相關聯:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
).RouteHandler = new MyRouteHander();
現在如果您要求/home/users
這是將被提供的Home
控制器的10個動作。
如果我做了一個switch語句並不意味着我需要事先知道這些URI嗎? – BigOmega 2011-06-15 18:23:52
還不完全。您有控制器手動處理路由。 – 2011-06-15 18:40:16