码迷,mamicode.com
首页 > Web开发 > 详细

mvc路由

时间:2015-07-02 23:56:16      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

      routes.MapRoute(
                name: "blog",
                //包含参数的url
                url: "{year}-{month}-{day}",
                defaults: new { Controller = "blog", Action = "index" },
                //参数的约束
                constraints: new { year = @"\d{4}", month = @"\d{2}", day = @"\d{2}" }
                //namespaces: new string[]{}
                );


            routes.MapRoute(
                "Test",
                //不包含参数的url
                "i-am-home-page",
                new { controller = "Home", action = "Index" }
                );

或自定义route类,一条路由一个类

  public class MyRouter : RouteBase
    {
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            //home-index
            //home-index-123
            var virtualPath = httpContext.Request.AppRelativeCurrentExecutionFilePath;
            virtualPath = virtualPath.Substring(2).Trim();
            string[] paths = virtualPath.Split(-);

            var data = new RouteData(this, new MvcRouteHandler());
            data.Values.Add("controller", paths[0]);
            data.Values.Add("action", paths[1]);
            if (paths.Length > 2)
            {
                data.Values.Add("id", paths[2]);
            }
            return data;
        }

        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            if (!values.ContainsKey("controller") || values["controller"].ToString().ToLower() != "home")
            { return null; }
            if (!values.ContainsKey("action") || values["action"].ToString().ToLower() != "index")
            { return null; }

            var path = values["controller"].ToString() + "-" + values["action"].ToString();
            if (!string.IsNullOrEmpty(values["id"].ToString()))
            { path += "-" + values["id"].ToString(); }

            return new VirtualPathData(this, path);
        }
    }

 

mvc路由

标签:

原文地址:http://www.cnblogs.com/tgdjw/p/4617313.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!