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 like URLs with attribute routing.

As you know 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 we need to understand structure of URLs of Stackoverflow. Let’s take example of following question URL which I have answered on

and let’s take another example

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

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


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


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.


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.


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


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.


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.


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



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)
                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.
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.


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

You can find whole source code for this blog post at following GitHub URL
Hope you like it. Stay tuned for more!!


  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

  2. Nice one..

    Also Jeff explains how they generate friendly urls;


Post a Comment

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

Popular posts from this blog

How to create Rest API(Web API) with ASP.NET Core 1.0

Creating PDF with ASP.Net MVC and RazorPDF

Solution: gulp is not recognized as internal or external command- Visual Studio