Web browser / device based ASP.NET MVC route (e.g. iPhone)

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

I am going to set up alternative actions and views for some parts of my website, if available from the iPhone, to optimize the display and functionality. I do not want to create a completely separate project for the iPhone, although most sites work fine on any device.

Any idea on how to do this?

+7
c # asp.net-mvc asp.net-mvc-routing
source share
3 answers

Mix: Mobile websites with ASP.NET MVC and mobile browser definition file

I don't know if this helps above since I haven't watched it yet.

And this one:

How to change ASP.NET MVC views based on device type?

+1
source share

You can create a route restriction 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 force the restriction on one of these routes:

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

Then you can create another route pointing to the controller with the same name in another namespace with or without a different restriction.

+1
source share

The best bet is 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() 
0
source share

All Articles