MVC路由Route

本文探讨了ASP.NET MVC中路由的工作原理,从默认路由设置开始,详细介绍了如何添加并配置自定义路由。重点强调了自定义路由的位置顺序对其生效的重要性。

控制器方法:

        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);
        }
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值