控制器方法:
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);
}
}
}

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

被折叠的 条评论
为什么被折叠?



