ASP.NET MVC: Custom Constraints – Matching the User Agent String

I have been really diving into routing with ASP.NET MVC and inevitably I came to the topic of custom constraints on routes. One of the really nice applications of custom constraints is matching a string contained within the client’s user agent string sent along with the request from the browser. For those that don’t know, the user agent is a string that is sent from the browser with information such as the type of browser used to make the request, the operating system of the client, and for most mobile phone browsers, the type of phone making the request. Check out to see a detailed explanation of your browser’s user agent string.

If you have a web application that should render differently on a mobile phone browser, say the iPhone, you can check the user agent string to see if the request is coming from an iPhone and if it is, you can direct it accordingly. To do such a thing in ASP.NET MVC, first we need to create a UserAgentConstraint class implementing the IRouteConstraint interface that will check to see if a given string is found within the client’s user agent string.

public class UserAgentConstraint : IRouteConstraint
    public string _stringInUserAgent;
    public bool _caseSensitive;

    public UserAgentConstraint(string stringInUserAgent, bool caseSensitive)
        this._stringInUserAgent = stringInUserAgent;
        this._caseSensitive = caseSensitive;

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        if (httpContext.Request.UserAgent == null)
            return false;

        // Check to see if the indicate string is found within the client's user agent string
        if (_caseSensitive)
            return httpContext.Request.UserAgent.Contains(_stringInUserAgent);

        // If not case sensitve, make everything lowercase and then check    
        return httpContext.Request.UserAgent.ToLower().Contains(_stringInUserAgent.ToLower());

When a constraint is checked, the Match method is called and returns whether or not the constraint is satisfied.

Now when defining the route, simply set the constraint for the user agent as a new instance of the UserAgentConstraint class matching the word iphone.

public static void RegisterRoutes(RouteCollection routes)

        null, // Route name
        "Home", // URL to match
        new { controller = "Home", action = "IndexIPhone" }, // Parameter defaults
        new { userAgent = new UserAgentConstraint("iphone", false) }    // Constraints

The above route, a rather dull example, simply directs the request to an action method in the Home controller named IndexIPhone where presumably the same logic resides for non-iPhone requests. In reality, you would probably want to separate these controllers into separate namespaces. Fortunately, you can also specify another RouteValueDictionary that lets the application know which namespace to look in when searching for the controller, but we will leave that for another time.

3 Responses to “ASP.NET MVC: Custom Constraints – Matching the User Agent String”

  1. william Says:

    Could you provide a download link to the code?

    • Nick Olsen Says:

      The entire code is above. All you need to do is create a new class in your project named UserAgentConstraint and copy and paste the first code segment into that class. Then in your Gobal.asax file, modify the RegisterRoutes method to include line 9 in the second code segment.

      Hope that helps.

  2. In, Is there a way to differentiate between IE7 users and IE8 users that are in compatibility mode? | PHP Developer Resource Says:

    […] perform these checks, consult the following tutorial, replacing all of this nonsense about iPhones and mobile devices with the browsers you’re […]

Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: