ASP.NET MVC Routing Question

前端 未结 6 2114
悲哀的现实
悲哀的现实 2021-02-02 17:08

I must be dense. After asking several questions on StackOverflow, I am still at a loss when it comes to grasping the new routing engine provided with ASP.NET MVC. I think I\'v

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-02 17:52

    Here is an alternative way to standar route registration:

    1. Download RiaLibrary.Web.dll and reference it in your ASP.NET MVC website project

    2. Decoreate controller methods with the [Url] Attributes:

    public SiteController : Controller
    {
        [Url("")]
        public ActionResult Home()
        {
            return View();
        }
    
        [Url("about")]
        public ActionResult AboutUs()
        {
            return View();
        }
    
        [Url("store/{?category}")]
        public ActionResult Products(string category = null)
        {
            return View();
        }
    }
    

    BTW, '?' sign in '{?category}' parameter means that it's optional. You won't need to specify this explicitly in route defaults, which is equals to this:

    routes.MapRoute("Store", "store/{category}",
    new { controller = "Store", action = "Home", category = UrlParameter.Optional });
    

    3. Update Global.asax.cs file

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
            routes.MapRoutes(); // This do the trick
        }
    
        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }
    }
    

    How to set defaults and constraints? Example:

    public SiteController : Controller
    {
        [Url("admin/articles/edit/{id}", Constraints = @"id=\d+")]
        public ActionResult ArticlesEdit(int id)
        {
            return View();
        }
    
        [Url("articles/{category}/{date}_{title}", Constraints =
             "date=(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])")]
        public ActionResult Article(string category, DateTime date, string title)
        {
            return View();
        }
    }
    

    How to set ordering? Example:

    [Url("forums/{?category}", Order = 2)]
    public ActionResult Threads(string category)
    {
        return View();
    }
    
    [Url("forums/new", Order = 1)]
    public ActionResult NewThread()
    {
        return View();
    }
    

提交回复
热议问题