Skip to main content 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

Recently Microsoft has released ASP.NET Core 1.0 RC2, I am getting lots of request from readers that about creating Web API. So I thought it will be a good idea to write a blog post about how to create Rest API(Web API) with ASP.NET Core 1.0.

So let’s get started via creating an ASP.NET Core 1.0 Web Application like following.

Once you click on ASP.NET Web Application, It will ask whether you need to create Web Application or Web API application. We are going to Web API so I am going to select Web API Application like following. Please note that in ASP.NET Core 1.0 there is no separate libraries or DLLs required for creating web APIs. This is just a project template.

Now once you click on OK It will create a Web API application with default values controller and program.cs.  As you know Program.cs is now starting point for the ASP.NET Core 1.0 application so It contains all the required configuration and startup items. Following is a code for that.
using System.IO; using Microsoft.Asp…

How to use migration with Entity Framework Core

Entity framework core is  the lightweight, extensible and cross-platform version of Entity Framework. Before some time, Microsoft has Released a new version of Entity Framework RC2. I have written a couple of blog post about Entity framework code first migration earlier for Entity framework 6.0. So there was a couple of request coming for writing a blog post about Entity Framework Core RC2 migration. So I thought it will be a good idea to give an overview how database migration works in Entity Framework Core RC2. This post will cover a basic scenario where we are going to create the database with existing ASP.NET Identity migration and then we are going to create a new model and have that migration applied in the database.

How to use Entity Framework Migrations: Let’s get started, To demonstrate entity framework core migrations, I am going to create a sample core web application like following.

Once we select core application it will appear the following dialog.

Now w…

Creating PDF with ASP.Net MVC and RazorPDF

Update: I have written a new blog post about better approach to create a PDF with mvc- You can find that following location.- A Better Solution to create PDF with Rotativa and ASP.NET MVC
In this post we are going to learn how we can easily create PDF from ASP.Net application with the help of Razor PDF NuGet package.

About Razor PDF:
This NuGet package is created by Al Nyveldt It internally uses ITextSharp an open source PDF convertor library. RazorPDF uses Razor View engine to create iTextXML which is in tern used to produce PDF file. You can get more information about that at below link.

Example(Creating PDF with ASP.Net MVC):
So what we are we waiting for ? Let’s create a simple example. To create example first thing we need to a create and ASP.Net MVC application.