Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Route based on Web Browser/Device (e.g. iPhone)

Is it possible, from within ASP.NET MVC, to route to different controllers or actions based on the accessing device/browser?

I'm thinking of setting up alternative actions and views for some parts of my website in case it is accessed from the iPhone, to optimize display and functionality of it. I don't want to create a completely separate project for the iPhone though as the majority of the site is fine on any device.

Any idea on how to do this?

like image 498
Alex Avatar asked May 27 '10 05:05

Alex


2 Answers

Mix: Mobile Web Sites with ASP.NET MVC and the Mobile Browser Definition File

Don't know if the above helps as I havn't watched it yet.

And this one;

How Would I Change ASP.NET MVC Views Based on Device Type?

like image 149
griegs Avatar answered Sep 24 '22 23:09

griegs


You can create a route constraint class:

public class UserAgentConstraint : IRouteConstraint
{
    private readonly string _requiredUserAgent;

    public UserAgentConstraint(string agentParam)
    {
        _requiredUserAgent = agentParam;
    }
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        return httpContext.Request.UserAgent != null &&
               httpContext.Request.UserAgent.ToLowerInvariant().Contains(_requiredUserAgent);
    }
}

And then enforce the constraint to one of the routes like so:

      routes.MapRoute(
           name: "Default",
           url: "{controller}/{action}/{id}",
           defaults: new {id = RouteParameter.Optional},
           constraints: new {customConstraint = new UserAgentConstraint("Chrome")},
           namespaces: new[] {"MyNamespace.MVC"}
           );

You could then create another route pointing to a controller with the same name in another namespace with a different or no constraint.

like image 38
elolos Avatar answered Sep 22 '22 23:09

elolos