MVC路由Route

来源:互联网 发布:美利达勇士300d淘宝 编辑:程序博客网 时间:2024/06/02 01:31

控制器方法:

        public ActionResult Index(string controller, string action, int id)        {            ViewBag.Name1 = controller;            ViewBag.Name2 = action;            ViewBag.Name3 = id;            return View();        }


一、MVC新建项目后会有一个默认路由:

routes.MapRoute(                name: "Default",                url: "{controller}/{action}/{id}",                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }            );

那么访问地址为:http://localhost:22631/home/index/1

二、添加一个自定义路由,记得自定义路由一定要放在默认路由上边,放置顺序很重要

            routes.MapRoute(                name: "DefaultX",                url: "X{controller}/{action}/{id}",                namespaces: new string[] { "IceCreamRouteTest.Controllers" },                defaults: new { id = UrlParameter.Optional }                );
那么访问地址为:http://localhost:22631/xhome/index/1

三、自定义路由

            routes.MapRoute(                name: "Default",                url: "{controller}/{action}/{id}",                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, httpMethod = new HttpMethodConstraint("POST") },                namespaces: new string[] { "IceCreamRouteTest.Controllers" }//,                , constraints: new { customConstraint2222 = new MyRouteConstraint("Chrome") }            //constraints: new { id = @"\d+" }            //constraints: new { id = new IntRouteConstraint() }            //,constraints: new MyRouteConstraint("Chrome")            //, constraints: new { controller = new MyRouteConstraint("Chrome") }            //OK            );

namespace IceCreamRouteTest.Models.Filters{    public class MyRouteConstraint : IRouteConstraint    {        private string requiredUserAgent;        public MyRouteConstraint(string agentParam)        {            requiredUserAgent = agentParam;        }        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)        {            return httpContext.Request.UserAgent.Contains(requiredUserAgent);        }    }}




原创粉丝点击