7

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?

Alex
  • 75,813
  • 86
  • 255
  • 348
  • This can help you http://www.hanselman.com/blog/IntroducingASPNETFriendlyUrlsCleanerURLsEasierRoutingAndMobileViewsForASPNETWebForms.aspx – Ammar Sep 12 '12 at 13:28

3 Answers3

1

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.

elolos
  • 4,310
  • 2
  • 28
  • 40
1

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?

Community
  • 1
  • 1
griegs
  • 22,624
  • 33
  • 128
  • 205
0

Best bet would be a custom action filter.

All you have to do is inherit from ActionMethodSelectorAttribute, and override the IsValidRequest class.

public class [IphoneRequest] : ActionMethodSelectorAttribute
    {
        public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
        {
             // return true/false if device is iphone

Then in your controller

[IphoneRequest]
public ActionResult Index()
RPM1984
  • 72,246
  • 58
  • 225
  • 350
  • Oh and i think to work out if the device is iphone: string agent = controllerContext.HttpContext.Request.UserAgent; return agent.Contains("iPhone") – RPM1984 May 27 '10 at 06:07