Saturday, August 23, 2014

Stackoverflow.com like URLs with attribute routing in ASP.NET MVC

Before some time I have blogged about Attribute Routing features of ASP.NET MVC 5.x version.  In this blog we are going to learn how we can create stackoverflow.com like URLs with attribute routing.

As you know www.stackoverflow.com is one of the most popular questions answer site where you can ask questions and almost get the answers of your questions. So to create URLs like www.stackoverflow.com we need to understand structure of URLs of Stackoverflow. Let’s take example of following question URL which I have answered on stackoverflow.com

http://stackoverflow.com/questions/24133693/can-i-use-signalr-2-x-with-net-4-0-if-i-am-using-microsoft-bcl-upgrading-from

and let’s take another example

http://stackoverflow.com/questions/23739256/the-advantage-of-formsauthentication-class-over-session-variable

If you compare and understand structure of this URLs. You will know that there will be a two things which will be dynamic for this URLS.

Here 24133693 and 23739256 denotes Id of question
And can-i-use-signalr-2-x-with-net-4-0-if-i-am-using-microsoft-bcl-upgrading-from and the-advantage-of-formsauthentication-class-over-session-variable part denotes the title of the question.

Creating ASP.NET application to create URLS like stackoverflow.com


Let’s first create a new ASP.NET Application like following.

StackOverFlowroutingprojectaspnetmvc

We are going to use ASP.NET MVC so I have selected MVC as following.

asp-net-mvc-project-attribute-routing-like-stackoverflow

Now it’s time to create model classes so if you observe stackoverflow question structure there are three main parts for creating a question like below.

stack-overflow-question-structure

Title of a question, Description of Question and Tags. Here we are going to ignore tags as it will be out of context for this project. So based on following structure we are going to have following model for questions.

namespace StackOverFlowRouting.Models
{
    public class Question
    {
        public int QuestionId { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
    }
}

Now it’s time to create a controller. Here we are going to create a controller with read write action.

question-controller-asp-net-routing-stackoverflow

Once you click on Add A popup for the for the controller name will appear.

controller-name-stackoverflowrouting

Once you click Add it will create controller with read write action. Here it will create a lot Action method but I have to only demo routing so we will take only index and detail Action Result methods and rest we will delete it. Here we are going to use only static data as I want to just demonstrate the routing mechanism. So we will create a List of question hardcoded. Just like following in controller constructor.
private readonly List<Question> _questions;
public QuestionController()
{
    _questions = new List<Question>
                {
                    new Question {QuestionId=1,
                                   Title="Title of first question",
                                   Description="Description of first question"},
                    new Question {QuestionId=1,
                                   Title="Title of second question",
                                   Description="Description of second question"},
                };
}
Following is a code for Index Action result.

public ActionResult Index()
{
    return View(_questions);
}
Now let’s add a view for Action Result Index like right click on view and Add View.

listing-question-view-stackoverflow-like-routing

It will create a view. Now it’s time to write a details action result code.
public ActionResult Details(int id)
{
    var question = _questions.FirstOrDefault(q => q.QuestionId == id);
    return View(question);
}
We can create details view like following.

DetailsView-action-result-stackoverflw-routing

Now let’s run application. All looks good as below but URL is not same as stackoverflow.com.

demo-application

details-page-demo-application

So It’s time to write attribute route for the same.  So first thing you need to do is to enable attributes routing from route.config.
using System.Web.Mvc;
using System.Web.Routing;

namespace StackOverFlowRouting
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes();
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}
So now routing is enabled. We can write our own route here. So let’s write route for details ActionResult.
[Route("Question/{id}/{*title}")]
public ActionResult Details(int id)
{
    var question = _questions.FirstOrDefault(q => q.QuestionId == id);
    return View(question);
}
Here you can see route attribute on details page action result which expects question id and title. *Title means from there all thing will be route. There is one more place where we need to change is Index.cshtml where we need to pass title like following.
@Html.ActionLink("Details", "Details", new { id=item.QuestionId,title=item.Title })
Now let’s run detail page again.

detailspagewithspacetitle

Here you can see that now its showing title but still you can see %20 that is because we have not replaced space with dash(-) and remove extra character which invalid for URLs. For that we need to write a HTML helper.
using System.Text.RegularExpressions;
using System.Web.Mvc;
namespace StackOverFlowRouting.Helpers
{
    public static class TitleHelper
    {
        public static string ClearnUrl(this HtmlHelper htmlHelper, string title)
        {
            string cleanTitle = title.ToLower().Replace(" ", "-"); 
            //Removes invalid character like .,-_ etc
            cleanTitle = Regex.Replace(cleanTitle, @"[^a-zA-Z0-9\/_|+ -]", "");
            return cleanTitle;
        }
    }
}
Here you can see that I have replace space with dash(-) and use regular expression removing invalid URL characters. Now again we need to change details action link like following.
@Html.ActionLink("Details", "Details", new { id=item.QuestionId,title=Html.ClearnUrl(item.Title)})

Now once you run detail page you can see the URL just like stackoverflow.com.

detail-page-asp-net-routing-like-stackoverflow
You can find whole source code for this blog post at following GitHub URL
https://github.com/dotnetjalps/StackOverFlowAttributeRouting
Hope you like it. Stay tuned for more!!
Share:

6 comments:

  1. Hey Jalpesh

    good article.

    just one observation though - the title portion that you are talking about is technically called as "Slug" in an URL terminology. so its not a stackoverflow thingy :) its a common practice with most of the CMS i beleieve ... for e.g. wordpress follows the similar patterns when generating a blog url.

    just wanted to let you know.

    keep up the good work

    ReplyDelete
  2. Nice one..

    Also Jeff explains how they generate friendly urls;

    http://stackoverflow.com/questions/25259/how-does-stack-overflow-generate-its-seo-friendly-urls

    ReplyDelete

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews