How to configure wildcard routing in asp.net mvc 4 How to configure wildcard routing in asp.net mvc 4

How to configure wildcard routing in asp.net mvc 4

The Problem

You are trying to configure Widlcard routing (i.e. something like http://domain.com/SomeUserName/) and find it problematic.

The Cause

That is largely by design – wildcard routing is resource intensive and rarely needed.

The Solution

If you want to do it anyway, use the following routes

routes.MapRoute(“Default”, “”, new { controller = “Home”, action = “Index”, id = UrlParameter.Optional });
routes.MapRoute(“CatchAll”, “{*id}”, new { controller = “Home”, action = “Handle”, id = “” });

Things to note

 

  • The Catch-All route is AFTER the home route
  • The syntax is *id – this will ensure that the value of ID is sent to the “Handle” action
  • The purpose of this route is to throw control to the “Handle” action with the appropriate value – Handle must be set up to use that value.

 

Okay, after some more digging (and some failed integration tests) here is what you have to do

Add in the following routes

routes.MapRoute(“Handle”, “Home/Handle/{id}”, new { controller = “Home”, action = “Handle”, id = “” });
routes.MapRoute(“User”, “{*id}”, new { controller = “Home”, action = “Index”, id = “” });
routes.MapRoute(“Default”, “{controller}/{action}/{id}”, new { controller = “Home”, action = “Index”, id = UrlParameter.Optional });

And then create an action called “Handler”, and change your Index action on your home controller to look like this

public ActionResult Index(string id=””)
{
if (!string.IsNullOrWhiteSpace(id))
{
return RedirectToAction(“Handle”, new {@id = id});
}
else {
return View();
}

What does this do?  It routes all wildcard traffic to your Index controller, which then hands it off to the “Handle” Action.  You would think that you could just hand everything off to the Handle action, but if you do that, then your Index action becomes inaccessible,  and in some circumstances you get a recursive loop where the handle action is called endlessly.  That does show an interesting error screen though.

One annoying side effect of this course of action is the need to map out each and every route explicitly, otherwise the wildcard route will pick it up and hand it off to the “Handle” action, which will take it somewhere where you do not want it to go.

 

Written By Steve French

 

One response to “How to configure wildcard routing in asp.net mvc 4”

  1. This is great but show us some URL’s that it can handle, it’s hard to imagine it’s use of it is what I am looking for. Everyone writes articles on routes then fails to publish an example of the routes their code is meant to deal with?

Leave a Reply

Your email address will not be published. Required fields are marked *






Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.