Carlos Miguel Colanta Carlos Miguel Colanta - 1 year ago 47
ASP.NET (C#) Question

"Subreddit" style URL routing in ASP.NET MVC?

Reddit links are normally like this:<subreddit>/<topic>

meaning that, the subreddit can be anything depending on how the user created it.

Usually on ASP MVC, We can do it like this:


but what if I want it to be something like this:


Answer Source

The keyword for this feature is attribute routing in ASP.NET MVC. There is a lot of information availbale in blogs etc.

With the Route-Annotation you can decorate your action and define a mapping between URL parts and parameters for the action call.

public class ExampleController : Controller
    public ActionResult Topic(string subreddit, string topic)
         //Logic goes here

Furthermore the attribute routing has to be activted in the RouteConfig.cs with routes.MapMvcAttributeRoutes(); like

public class RouteConfig
    public static void RegisterRoutes(RouteCollection routes)


            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

Then you can call the Topic-Action of the ExampleController by http://localhost:PORT/r/reddit/topic.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download