Search code examples
asp.net-mvcroutesactionlink

Correctly rendering ActionLinks on MVC site with vanityURL


I need to create site where URL patterns allow for a personalized URL like www.mysite.com brings up the main portal.

www.mysite.com/customer1 brings the portal customized for that customer (same actions and controllers called the argument for customization will be pulled from URL).

I want the prefix '/customer1/' to be maintained in the URL all the time on all pages.

I have the following routes which work fine:

routes.MapRoute(
    name: "CompanyUrl",
    url: "{companyurl}/{controller}/{action}/{id}",
    defaults: new { companyurl = UrlParameter.Optional, controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

However, when I enter the site on the vanityURL so on www.mysite.com/customer1 all action links are rendered OK as

<a href="/customer1/Home/Contact">Contact</a>

but when I enter just www.mysite.com, all links are rendered as:

<a href="//Home/Testimonials">Testimonials</a> 

and I cannot navigate anywhere.

How can I get them to render correctly without the companyurl parameter and without the additional /?


Solution

  • Assuming I understood correctly, try this (though check if it works as expected throughout):

    • remove the default for {companyurl} - this makes it "mandatory" for that route (meaning it will not "match" your CompanyUrl route config if not present and fall through next config which is the Default config).

    So your "CompanyUrl" Route:

    routes.MapRoute(
        name: "CompanyUrl",
        url: "{companyurl}/{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
    

    Hth...