Cpurepair785
Cpurepair785

Reputation: 23

C#.NET MVC Route Aliasing

I've been searching and searching for away to make old URL like we used to do in aspx pages where you could have an alias pointing to a page like www.domain.com/my-great-alias point to www.domain.com/alias.aspx. I want to do the same thing in MVC but can not figure out how to make this happen in the route table. Where www.domain.com/my-great-alias would show up to the end user as such but point to www.domain.com/alias/2

Does this make sense to anyone else what I'm looking for?

// router

routes.MapRouteLowercase(
                            "Alias",
                            "{id}",
                            new
                            {
                                controller = "alias",
                                action = "select",
                                id = UrlParameter.Optional
                            }
                        );

// Alias controller

public ActionResult Select()
        {
            return View("select");
        }

// Recipe Controller

public ActionResult Select()
    {
        return View();
    }

Upvotes: 0

Views: 2339

Answers (1)

Matt Spinks
Matt Spinks

Reputation: 6698

You should be able to do this utilizing route config and parameters (as long as it's in the same domain):

Routing

        routes.MapRoute(
            name: "AliasRoute",
            url: "{id}",
            defaults: new { controller = "Alias" }
        );

Controller

public class AliasController : Controller
{
    public ActionResult Index(string id)
    {
        //DO SOME DATABASE STUFF HERE TO LOOKUP THE CORRESPONDIND CONTROLLER AND ACTION
        var controllerAction = lookupControllerActionInDatabase(id);
        return View(controllerAction.ViewName);

        //OR

        //DO CONDITIONAL CHECKS HERE AND RETURN THE APPROPRIATE VIEW
        if (id == "my-great-alias") {
          return View("Alias");
        } else if (id == condition1) {
          return View("viewForCondition1");
        } else if (id == condition2) {
          return View("viewForCondition2");
        }
        //AND SO ON...
    }
}

Upvotes: 1

Related Questions