[Attribute] Routing in ASP.Net MVC 5 / WebAPI 2 (Part II)


In my last post I have discussed about the attribute routing and I believe that was quite enough to get started with the new featured offered both by MVC5 and WebAPI 2. In this post I will keep digging the same topic and together we will explore how we could impose certain constraints to get more control over routing.

Imposing Constraints

Imposing Constraints restrict how the parameters in the route template are matched. In the last post, I have shown how to search certain employee by their id. Now, lets say we also want the end user to search employee by Name. Also assume different view have be render in that case.

home/3 <–render “View A”
home/shahriar <–render “View B”

What we can do is to add another ActionResult which receives a string parameter. But only doing so does not solve our problem. We have to explicitly define and impose certain constraints to let the routing framwork work perfectly.

Notice the route carefully. In both cases routing framework hits the home controller and then based on the action parameter received it renders different view. If we just don’t explicitly tell the routing framework to impose certain constraints it just can’t fly you(the viewer) to the the appropriate action.

The general syntax for imposing certain constraint is {parameter:constraint}.

public class HomeController : Controller
      [Route("home/{id? : int}")]
      public ActionResult Employee(int id)
           //Logic goes here

      public ActionResult Employee(string name)
           //Logic goes here

Here, the first route will only be selected if the “id” segment of the URI is an integer. Otherwise, the second route will be chosen. (“?”) symbol specifies that this parameter is Optional.

Ken Egozi posted a nice article regarding Attribute routing and there he posted Complete list of constraints with some example that I have added below:

Constraint Description Example
alpha Matches uppercase or lowercase Latin alphabet characters (a-z, A-Z) {x:alpha}
bool Matches a Boolean value. {x:bool}
datetime Matches a DateTime value. {x:datetime}
decimal Matches a decimal value. {x:decimal}
double Matches a 64-bit floating-point value. {x:double}
float Matches a 32-bit floating-point value. {x:float}
guid Matches a GUID value. {x:guid}
int Matches a 32-bit integer value. {x:int}
length Matches a string with the specified length or within a specified range of lengths. {x:length(6)}
long Matches a 64-bit integer value. {x:long}
max Matches an integer with a maximum value. {x:max(10)}
maxlength Matches a string with a maximum length. {x:maxlength(10)}
min Matches an integer with a minimum value. {x:min(10)}
minlength Matches a string with a minimum length. {x:minlength(10)}
range Matches an integer within a range of values. {x:range(10,50)}
regex Matches a regular expression. {x:regex(^\d{3}-\d{3}-\d{4}$)}

Pay Close Attention : Some of the constraints, such as “min”, “maxlength”, “minlength” take arguments in parentheses.

To apply multiple constraints to a parameter, separated each constraint by a colon.

Rrestricting specific actions to specific HTTP verbs:
Existing attributes (e.g. [HttpGet], [HttpPost] and [AcceptVerbs]) are allowed 🙂

And this brings to end of this topic. I have tried to cover up almost all the relevant major things regarding attribute routing but yet there has some mini tips and tricks that hasn’t been discussed here. I leave up those those tiny things for you. Hope you could figure out those tiny things by yourself. Happy coding 🙂

Additional Resources:

  1. Maarten Balliauw’s blog
  2. Attribute routing in Web api 2



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s