.NET 中的移动浏览器设备检测 [英] mobile browser device detection in .NET

查看:29
本文介绍了.NET 中的移动浏览器设备检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始创建我的第一个移动版桌面网站,它是用 WebForms 编写的.

I'm just starting to create my first mobile version of a desktop website that was written in WebForms.

我当前的问题与移动设备/浏览器检测有关.

My current question has to do with mobile device/browser detection.

我想确定的是 a) 如果您的设备是移动设备 b) 什么操作系统 (Android/IOS/etc) 以防我需要根据操作系统处理任何不同的事情 c) 什么屏幕尺寸(用于加载不同的样式表)

What I'm trying to determine is a) If your device is mobile b) What OS (Android/IOS/etc) in case I need to handle anything differently based on the OS and c) What screen size (for loading different stylesheets)

推荐答案

通过查看 useragent 字符串来检测浏览器的类型是最简单的.该字符串中的关键字将有助于检测浏览器.UserAgentString.com 维护一个完整的用户代理字符串列表,但您需要查看的主要内容因为只是几个关键字.

Detecting the type of browser is simplest by looking at the useragent string. Key words in that string will help detect the browser. UserAgentString.com maintains a thorough list of useragent strings, but the main thing you need to look for are only a few keywords.

例如,blackberry"一词仅在从 Blackberry 设备浏览时才会出现.与 iPad 和 iPhone 类似.Android 设备都在用户代理字符串中显示android",但它们通过包含手机的关键字mobile"来区分平板电脑和手机.

For example, the word "blackberry" only ever shows up when browsing from a Blackberry device. Similar with iPad and iPhone. Android devices all show "android" in the useragent string, but they distinguish between tablets and phones by inclusion of the keyword "mobile" for phones.

以下是我们在移动应用程序中检测台式机、手机和平板电脑的方法:

Here's how we detect Desktops, Phones, and Tablets in our mobile application:

    public enum DeviceType
    {
        Desktop,
        Tablet,
        Phone
    }

    public static DeviceType UserAgentToDeviceType(string userAgent)
    {
        if (userAgent.ToLowerInvariant().Contains("blackberry"))
            return DeviceType.Phone;

        if (userAgent.ToLowerInvariant().Contains("iphone"))
            return DeviceType.Phone;

        if (userAgent.ToLowerInvariant().Contains("ipad"))
            return DeviceType.Tablet;

        if (userAgent.ToLowerInvariant().Contains("android"))
        {
            if (userAgent.ToLowerInvariant().Contains("mobile"))
                return DeviceType.Phone;
            else
                return DeviceType.Tablet;
        }

        return DeviceType.Desktop;
    }

如果您使用的是 jQuery Mobile 之类的东西,则无论设备类型如何,网站都将针对移动外观进行定制,它将处理不同设备上 JavaScript 引擎之间的差异.

If you are using something like jQuery Mobile, the site will be customized for mobile appearance regardless of device type, and it will handle differences between the JavaScript engine on different devices.

这篇关于.NET 中的移动浏览器设备检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆