如何检查用户代理是否为iPad或iPhone?

37

我正在使用C# asp.net网站。

如何检查用户是否使用ipad或iphone?如何检查平台?

例如,如果用户从iPad输入网站,则希望显示“Hello ipad user”。


2
你能具体说明一下吗?你是在编写一个使用MonoTouch部署到这些设备的C#应用程序吗?还是在编写一个C# ASP .NET网站,这些设备将要访问它? - David
我猜这不是一个C#应用程序,而是一个C# Web服务器(ASP?)你应该检查UserAgent。 - RvdK
是的,它是C# ASP.NET Web。 - avnic
1
维基百科在这里介绍了UserAgent:http://en.wikipedia.org/wiki/User_agent。 - Mike Chess
9个回答

73

2020年7月17日更新: 看起来苹果已经将iPad一词删除,现在使用Macintosh代替

更新: 由于iPad用户代理包含@Rob Hruska 提到iPhone一词:

Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10

而iPhone用户代理大致是这样:

Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7

因此,正确的方法是检查是否包含iPhone;iPad;来识别设备:

var userAgent = HttpContext.Current.Request.UserAgent.ToLower();
if (userAgent.Contains("iphone;"))
{
    // iPhone
}
else if (userAgent.Contains("ipad;") || userAgent.Contains("macintosh;"))
{
    // iPad
}
else
{
    // Think Different ;)
}

2
这个解决方案其实还不错,对我有用,不知道为什么没有被选为最佳答案... 呵呵 我只是复制粘贴了一下,'Alex' 这个帮了我.. 谢谢! :) - visual
1
嘿,Alex,它也帮助了我。+1。 - Jack
5
这不会将iPad识别为iPhone吗?因为iPad用户代理中包含“...CPU iPhone…”? - Rob Hruska
7
需要先检查 iPad,再检查 iPhone,因为 iPad 中也包含 iPhone。否则可能会始终得到 iPhone 作为答案。 - user1693593
1
@Ken-AbdiasSoftware,需要检查是否为“iPhone;”或“iPad”。顺序不重要。 - Oleks
显示剩余7条评论

22
针对iPad的用户代理类似于以下内容:

Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10

而针对iPhone则是这样的:

Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3

还有许多其他版本,无论是iPhone 3还是4,因此最好只进行iPhone和iPad的子字符串搜索,如另一个答案所建议的。

搜索“iPhone”也会将Windows手机识别为iPhone。请参见下面的答案。 - bytedev
1
新的iPad在它们的用户代理中看起来像Macintosh。请参见https://getpolarized.io/2019/12/21/Apple-Lying-About-User-Agent-in-iPad-Pro.html。 - malex
这个答案已经不正确了,因为iPadOS默认情况下从用户代理字符串中删除了“iPad”。现在,“设置-> Safari->请求桌面网站->所有网站”默认为开启状态。 - PerpetualStudent

5
这些设备的用户代理包括相应的"iPod"、"iPad"或"IPhone"。请注意,有几个用户代理在使用中,所以精确匹配是不明智的 - 但可以从您的设备上查看头部信息来进行检查,请访问http://whatsmyuseragent.com。因此,请检查头部信息中的用户代理。

4

您可以通过获取用户代理来实现。

string ua = Request.UserAgent;
if (ua != null && (ua.Contains("iPhone") || ua.Contains("iPad")))
{
...
...
...
}

4

我建议先尝试使用WURFLhttp://wurfl.sourceforge.net/

他们有.NET API和非常好的代码示例。http://wurfl.sourceforge.net/dotnet_index.php

可以帮助您的类名为WURFLManager,具有以下方法:

enter image description here

使用WURFL http://wurfl.sourceforge.net/dotnet_index.php

如果您使用asp.net mvc,可以使用ActionFilter

public class MobileActionFilterAttribute : ActionFilterAttribute
{
    // The WURFL database contains information about a huge number of devices and mobile browsers.
    // http://wurfl.sourceforge.net/
    // http://wurfl.sourceforge.net/dotnet_index.php
    // http://wurfl.sourceforge.net/help_doc.php

    private static readonly IWURFLManager WurflManager;

    static MobileActionFilterAttribute ()
    {
        IWURFLConfigurer configurer = new ApplicationConfigurer();
        WurflManager = WURFLManagerBuilder.Build(configurer);
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpRequestBase request = filterContext.RequestContext.HttpContext.Request;

        // We don't have ARR server for dev environment, so we still need to check to see if the current domain name is the mobile site.
        if (request.Url.AbsoluteUri.StartsWith(SiteConfiguration.Current.MobileSiteAddress, StringComparison.OrdinalIgnoreCase))
        {
            return;
        }

        // Creates a WURFLRequest object from an ASP.NET HttpRequest object
        WURFLRequest wurflRequest = WURFLRequestFactory.CreateRequest(HttpContext.Current.Request);

        // Indicates whether the current user agent string refers to a desktop agent.
        if (wurflRequest.IsDesktopRequest)
            return;

        // Get the information about the device
        IDevice deviceInfo = WurflManager.GetDeviceForRequest(wurflRequest);

        // Tells you if a device is a tablet computer (iPad and similar, regardless of OS)
        bool isTablet = string.Equals(deviceInfo.GetCapability("is_tablet") ?? string.Empty, "true", StringComparison.OrdinalIgnoreCase);

        if (isTablet)
        {
            // so we don't show the mobile site for iPad.
            return;
        }

        // Indicates whether the current user agent string refers to a mobile device.
        bool isMobileRequest = wurflRequest.IsMobileRequest;

        // Tells you if a device is wireless or not. Specifically a mobile phone or a PDA are considered wireless devices, a desktop PC or a laptop are not
        bool isWirelessDevice = string.Equals(deviceInfo.GetCapability("is_wireless_device") ?? string.Empty, "true", StringComparison.InvariantCultureIgnoreCase);

        if (isMobileRequest && isWirelessDevice)
        {
            // we can redirect to the mobile site!
            filterContext.Result = new RedirectResult(SiteConfiguration.Current.MobileSiteAddress);
        }
    }
}

还有51Degrees.Mobi。Steve Sanderson在他的博客中介绍了如何使用它。

http://blog.stevensanderson.com/2010/12/17/using-51degreesmobi-foundation-for-accurate-mobile-browser-detection-on-aspnet-mvc-3/

51Degrees.Mobi Foundation是一个开源.NET项目,它增强了Request.Browser,使其从无线通用资源文件(WURFL)获取信息 - 这是最全面和最新的移动设备信息数据库之一。令人兴奋的消息是,现在可以将51Degrees.Mobi Foundation作为NuGet包使用,因此安装和更新非常容易。


3

注意Windows手机!出于某种奇怪的原因,许多Windows手机在用户代理中会显示“像iPhone”。因此,您需要检查:

public bool IsIPhone
{
    get
    {
        if (!UserAgent.ToUpper().Contains("LIKE IPHONE"))
        {
            return UserAgent.ToUpper().Contains("IPHONE");
        }
        return false;
    }
}

示例Windows手机用户代理(来自Lumia 735):

"Mozilla/5.0(移动设备;Windows Phone 8.1;Android 4.0;ARM;Trident/7.0;Touch;rv:11.0;IEMobile/11.0;NOKIA;Lumia 735)like iPhone OS 7_0_3 Mac OS X AppleWebKit/537(KHTML,like Gecko)Mobile Safari/537"


2

iOS 13 开始,用户代理变成了Mac OS,例如:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Safari/605.1.15

"Original Answer" 的翻译是 "最初的回答"。


是的,那么我们现在如何检测iOS、iPad和iPhone呢? - Justin Putney
@JustinPutney 这是我的问题链接:https://dev59.com/a1MI5IYBdhLWcg3wJ4AS - zvi

0

你可以从Request.UserAgent获取客户端操作系统数据,包括操作系统名称和版本。

  public static string GetClientOS(string ua, string platform)
    {

        if (ua.Contains("Android"))
            return string.Format("Android {0}", GetMobileVersion(ua, "Android"));

        if (ua.Contains("iPad"))
            return string.Format("iPad OS {0}", GetMobileVersion(ua, "OS"));

        if (ua.Contains("iPhone"))
            return string.Format("iPhone OS {0}", GetMobileVersion(ua, "OS"));

        if (ua.Contains("Linux") && ua.Contains("KFAPWI"))
            return "Kindle Fire";

        if (ua.Contains("RIM Tablet") || (ua.Contains("BB") && ua.Contains("Mobile")))
            return "Black Berry";

        if (ua.Contains("Windows Phone"))
            return string.Format("Windows Phone {0}", GetMobileVersion(ua, "Windows Phone"));

        if (ua.Contains("Mac OS"))
            return "Mac OS";

        if (ua.Contains("Windows NT 5.1") || ua.Contains("Windows NT 5.2"))
            return "Windows XP";

        if (ua.Contains("Windows NT 6.0"))
            return "Windows Vista";

        if (ua.Contains("Windows NT 6.1"))
            return "Windows 7";

        if (ua.Contains("Windows NT 6.2"))
            return "Windows 8";

        if (ua.Contains("Windows NT 6.3"))
            return "Windows 8.1";

        if (ua.Contains("Windows NT 10"))
            return "Windows 10";

        return  platform + (ua.Contains("Mobile") ? " Mobile " : "");
    }

    public static string GetMobileVersion(string userAgent, string device)
    {
        var temp = userAgent.Substring(userAgent.IndexOf(device) + device.Length).TrimStart();
        var version = string.Empty;

        foreach (var character in temp)
        {
            var validCharacter = false;
            int test = 0;

            if (int.TryParse(character.ToString(), out test))
            {
                version += character;
                validCharacter = true;
            }

            if (character == '.' || character == '_')
            {
                version += '.';
                validCharacter = true;
            }

            if (validCharacter == false)
                break;
        }

        return version;
    }

0
private static final Pattern IPHONE_AGENT = Pattern.compile(".*iPad.*|.*iPhone.*|.*iPod.*");    

String userAgent = request.getHeader("User-Agent");
if (userAgent != null && IPHONE_AGENT.matcher(userAgent).matches()) {
    // do something
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接