【问题标题】:ASP.NET MVC Route based on Web Browser/Device (e.g. iPhone)基于 Web 浏览器/设备(例如 iPhone)的 ASP.NET MVC 路由
【发布时间】:2010-05-27 05:57:35
【问题描述】:

是否可以从 ASP.NET MVC 中根据访问设备/浏览器路由到不同的控制器或操作?

我正在考虑为我网站的一些部分设置替代操作和视图,以防从 iPhone 访问它,以优化它的显示和功能。我不想为 iPhone 创建一个完全独立的项目,因为该网站的大部分内容在任何设备上都可以。

你知道怎么做吗?

【问题讨论】:

标签: c# asp.net asp.net-mvc asp.net-mvc-routing


【解决方案1】:
【解决方案2】:

你可以创建一个路由约束类:

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);
    }
}

然后像这样对其中一个路由强制执行约束:

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

然后,您可以创建另一个路由,指向另一个名称空间中具有不同约束或没有约束的同名控制器。

【讨论】:

    【解决方案3】:

    最好的选择是自定义操作过滤器。

    您所要做的就是从ActionMethodSelectorAttribute 继承,并覆盖IsValidRequest 类。

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

    然后在你的控制器中

    [IphoneRequest]
    public ActionResult Index()
    

    【讨论】:

    • 哦,如果设备是 iphone,我想弄清楚: string agent = controllerContext.HttpContext.Request.UserAgent;返回 agent.Contains("iPhone")
    猜你喜欢
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 2023-03-22
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多