Carlos Miguel Colanta
Carlos Miguel Colanta

Reputation: 2823

"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 ?

Upvotes: 0

Views: 159

Answers (1)

Ralf B&#246;nning
Ralf B&#246;nning

Reputation: 15425

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.

Upvotes: 4

Related Questions