Pretty URL ASP.NET MVC

前端 未结 3 1121
不知归路
不知归路 2020-12-29 00:45

How can I get pretty urls like localhost:8888/News/Example-post instead of localhost:8888/Home/Details/2

My HomeController has the following for the Details method

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-29 01:20

    What I do on my sites is that I check the URL against either the Page Title or Page Stub in cases where the page titles could have the same name for instance if you have a site that posts a "Picture of the Week" you may want to use a stub instead of title as you'll have multiples named the same thing.

    URLs look like this: http://mySite.com/Page/Verse-of-the-Week

    Global.asax contains this:

    routes.MapRoute("Pages", "{controller}/{pageID}", new { controller = "Page", action = "Index", pageID = "Home" });
    

    PageController is this:

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index(string pageID)
        {
            if (pageID == null)
            {
                pageID = pageRepository.HomeOrLowest();
            }
            var p = pageRepository.ByStub(pageID);
            if (p == null) { return RedirectToAction("NotFound", "Error"); }
            return View(p);
        }
    

    The repository looks like this:

        private static Func _byStub =
            CompiledQuery.Compile((mvCmsContext context, string pageTitle) =>
                (from p in context.Pages
                 where p.pageTitle.Replace(" ", "-") == pageTitle
                 select p).SingleOrDefault());
        public Page ByStub(string pageTitle)
        {
            return _byStub(context, pageTitle);
        }
    

    I hope that helps.

    Edit to add duplicate handling:

        private static Func _pageExists =
            CompiledQuery.Compile((mvCmsContext context, string pageTitle) =>
                (from p in context.Pages
                 where p.pageTitle.Replace(" ", "-") == pageTitle
                 select p).Count());
        public bool PageExists(string pageTitle)
        {
            return Convert.ToBoolean(_pageExists(context, pageTitle));
        }
    

    Validates like this:

            IValidationErrors errors = new ValidationErrors();
            if (CreateOrEdit == "Create")
            {
                if (pageRepository.PageExists(model.pageTitle) && !String.IsNullOrEmpty(model.pageTitle))
                    errors.Add("pageTitle", "A page with this title already exists.  Please edit it and try again.");
            }
    

提交回复
热议问题