views:

46

answers:

2

Hello! I'm using ASP.NET MVC to develop a website and I need to customize my URL to use a name that is not the name of my Controller.

I want to use this Class/Method names:

public class CompanyController:Controller {
    public ActionResult About() {
        return View();
    }
}

But I want to use the URL http://www.mysite.com/the-company/about-us to access my Controller/Method.

How should I proceed?

Thank you.

+2  A: 

You will use URL Routing:

http://www.asp.net/learn/mvc/tutorial-05-cs.aspx

routes.MapRoute(
                "AboutUs",                                           // Route name
                "the-company/about-us",                            // URL with parameters
                new { controller = "CompanyController", action = "About" }  // Parameter defaults
            );
Nissan Fan
+2  A: 

Since your question is mainly about controller naming I would (contrary to @Nissan Fan's answer) do at least this generalization, to make routing a bit more flexible and minimize the amount of routes, you'd have to define:

routes.MapRoute(
    "CompanyRoute",
    "the-company/{action}",
    new { controller = "Company", action = "About" }
);

Your controller should of course be written this way:

public class CompanyController : Controller
{
    [ActionName("about-us")]
    public ActionResult About()
    {
        return View("About");
    }
}
Robert Koritnik
While this is a reasonable alternative to hard routing the controller/action, having multiple routes is pretty efficient. I'm not a fan of wildcard routing as it makes route debugging a mess. You're essentially opening up any Action or public method on the CompanyController to access via your route add.
Nissan Fan
@Nissan Fan: Wise developers use action filters to avoid such security holes. I still tend to use generalized routes instead of having many single controller-action routes. You can always put `[NonAction]` attribute on controller methods that you don't want exposed (trat are not actions per se).
Robert Koritnik
@Robert Not saying your approach is either incorrect or wrong, it's just a personal perference to use implicit routing when appropriate. I think you're alternative solution shows a good feature which is ActionName aliases. Either way the questioner is gaining from the input your provided and I upticked you accordingly.
Nissan Fan
At first, I would like to thank you both!I have a little questions more about it: can I discard the 'new { controller = "Company", action = "About" }' parameter and just use the attributes [ActionName("")] on controller's method?
MCardinale
If you discard defaults, you will have problems, when someone will try to access: /the-company. **Which controller and which action should be executed?** That's why route defaults are for. They provide values when they're not provided within the request URL. Don't remove defaults.
Robert Koritnik
Thank you again!
MCardinale