[英]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? 从ASP.NET MVC中,是否可以基于访问设备/浏览器路由到不同的控制器或操作?
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. 我正在考虑为我的网站的某些部分设置替代操作和视图,以防从iPhone访问它,以优化它的显示和功能。 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. 我不想为iPhone创建一个完全独立的项目,因为大多数网站在任何设备上都可以。
Any idea on how to do this? 有关如何做到这一点的任何想法?
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. 然后,您可以创建另一个指向具有相同名称的控制器的路径,该控制器具有不同或没有约束的另一个命名空间
Mix: Mobile Web Sites with ASP.NET MVC and the Mobile Browser Definition File 混合:使用ASP.NET MVC的移动网站和移动浏览器定义文件
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? 我如何根据设备类型更改ASP.NET MVC视图?
Best bet would be a custom action filter. 最好的选择是自定义动作过滤器。
All you have to do is inherit from ActionMethodSelectorAttribute
, and override the IsValidRequest
class. 您所要做的就是从ActionMethodSelectorAttribute
继承,并重写IsValidRequest
类。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.