首页 > 代码库 > 路由如何生成URL

路由如何生成URL

 
public class MyRoute : RouteBase { public override RouteData GetRouteData(HttpContextBase httpContext) { RouteData route = new RouteData(this, new MvcRouteHandler()); route.Values.Add("Controller", "Home"); route.Values.Add("Action", "Index"); return route; } public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { if (values.ContainsKey("controller") && (string)values["controller"] == "Home" && values.ContainsKey("action") && (string)values["action"] == "Index") { return new VirtualPathData(this, "myurl/home/index");//生成自定义URL } else { return null; } } }

添加路由到路由集合中

 routes.Add("myRoute", new MyRoute());

新建控制器,以及对应的视图

  public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        } 
    }

视图如下:

<h2>Index</h2>
@Html.RouteLink("首页", new { controller = "Home", action = "Index" })

运行后生成如下结果:

路由如何生成URL