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?
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With