Carlos Miguel Colanta Carlos Miguel Colanta - 3 months ago 11
ASP.NET (C#) Question

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

Reddit links are normally like this:

https://www.reddit.com/r/<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:

local/controller/action?subreddit=subname&topic=topicname


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

local/controller/action/subname/topicname
?

Answer

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
{
    [Route("r/{subreddit}/{topic}")]
    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)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            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.