2

I want to create a RESTful API for my blog application but I can't tell how to map controllers like this.
How can it be done? Should Post be hardcoded in the URL pattern?

1 Answer 1

5

You could map a route like this:

routes.MapRoute(
        "ShowComments", // Route name
        "Post/{id}/Comments/{action}", // URL with parameters
        new { controller = "CommentsController", action = "Show" } // Parameter defaults
        );

There's nothing wrong with hardcoding URLs unless everything you add needs hardcoded URLs and they become unmaintainable.

What I understand is you want CommentsController called by only this route. You do not want it to be called by the default route. You can use IgnoreRoute for that.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute(“Comments/{action}/{id}”);
}

This will make sure CommentsController doesn't get called without the route we defined before. I hope that was what you were trying to do.

6
  • What does the use of brackets ([]) indicate vs braces ({})?
    – mxmissile
    Dec 22, 2010 at 17:03
  • Sorry for that. Both should have been braces. Dec 22, 2010 at 17:12
  • np, thought there was some cool functionality that I did not know about :-)
    – mxmissile
    Dec 22, 2010 at 17:15
  • The question is: Can't a controller have "sub-controllers"?
    – the_drow
    Dec 22, 2010 at 23:00
  • I'm sorry about that. Last sentence in your question made me think it was about routes. Maybe you want to give more details about the problem. Dec 23, 2010 at 17:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.