Slug URL in MVC

Creating a human friendly URL is one of the important goal in content management system. Recently one developer asked me this question. Like he always sees 'id' in URL in MVC application which is not human friendly. He mentioned stack-overflow example when explaining issue to me, so let’s discuss about this.
Open stack-overflow page

you will be redirected to

Notice the last part in the query, this is nothing but a slug that is being added in URL all the time. Technically both URL maps to same resource. And in URL number '40956081' is unique identifier.

I hope you know Stack-Overflow is also build using ASP.NET MVC. Let's build similar slug and similar behavior in your MVC application.

First you need to configure your route as give below:

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Question_Default",
                url: "question/{id}/{slug}",
                defaults: new { controller = "home", action = "question", id = UrlParameter.Optional, slug = UrlParameter.Optional }
            );
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "home", action = "index", id = UrlParameter.Optional }
            );
        }



Now you need to write slug redirect logic in MVC action or you can create action filter if you want this to be reusable.

        public ActionResult Question(int id, string slug)
        {
            // call database table to get question based on input 'id'
            // 'id' is primary key in database table
            // depending on unique slug all the time is not good idea
            // so, let's keep 'id' primary key and keep it using
            var question = QuestionExtension.GetQuestion(id);

            // check if database returned no question
            if (question == null)
                return Redirect("~/error/noquestion");

            // redirect on slug based url here only
            // or you can create action filter so that it works everywhere in your application
            if (string.IsNullOrEmpty(slug))
            {
                slug = question.Slug;
                return RedirectToRoute("Question_Default", new { id = id, slug = slug });
            }

            return View(question);
        }

And that's it, you are good to test this. I have uploaded this project on GitHub for you in case you would like to test my code.

Hope this helps.

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System