reverence12389
reverence12389

Reputation: 467

ASP.NET MVC map single controller to root of website

I am working on an ASP.NET MVC 5 website that has a public "marketing" website that contains somewhat static pages with information about the company, legal, social, contact us, etc. that a non-logged in user can access. Then, once logged in, there is a back end of the website that registered users have access to features.

Originally I had all the public "marketing" pages going to http://www.mywebsite.com/Marketing/About, http://www.mywebsite.com/Marketing/Social, etc.

However, the business wants all the "marketing" pages, to be accessible a single directory down from the root website, so the links above would be accessible with: http://www.mywebsite.com/About, http://www.mywebsite.com/Social, etc.

I know I can use the below approach to get it to work by registering individual routes for each "marketing" page like so:

        routes.MapRoute(
            "ShortAbout",
            "About",
            new { controller = "Marketing", action = "About" }
        );

        routes.MapRoute(
            "ShortSocial",
            "Social",
            new { controller = "Marketing", action = "Social" }
        );

However, since there are about 15 "marketing" pages, this seems inefficient and it seems like there must be a better way to do this.

I also tried a generic routing approach outlined here: http://www.wduffy.co.uk/blog/aspnet-mvc-root-urls-with-generic-routing/

but the problem with that approach was I had a "marketing" page, with the same name as a controller and it ended up forwarding the user to the marketing subdirectory. For example, I had a Controller called "MachineController", and in the "MarketingController" I had an action/page called "Machine", so it was forwarding the user to /Marketing/Machine using the approach in the above link.

Any other ideas? Thanks in advance.

Upvotes: 2

Views: 1726

Answers (1)

James Ellis-Jones
James Ellis-Jones

Reputation: 3092

I had exactly this problem. A much simpler but more hardcoded solution is

routes.MapRoute("MarketingPages", "{action}",
  new { controller = "Marketing" },
  new { action = @"About|Social" });

The last anonymous object constrains the route to match routes where action matches the supplied regular expression, which is simply a list of the urls you want to have marketing pages. Any other url like '/something' falls through to the routes below.

Upvotes: 1

Related Questions