.NET/C#实现识别用户访问设备的方法

本文实例讲述了.NET/C#实现识别用户访问设备的方法。分享给大家供大家参考,具体如下:

一、需求

需要获取到用户访问网站时使用的设备,根据不同设备返回不同类型的渲染页面。

二、实现前准备

通过NuGet把UAParser程序包添加到项目中

三、实现

新建UAParseUserAgent类文件,在这个文件中进行实现。

实现代码如下:

public class UAParserUserAgent
{
    private readonly static uap.Parser s_uap;
    private static readonly Regex s_pdfConverterPattern = new Regex(@"wkhtmltopdf", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
    # region Mobile UAs, OS & Devices
    private static readonly HashSet<string> s_MobileOS = new HashSet<string>
    {
      "Android",
      "iOS",
      "Windows Mobile",
      "Windows Phone",
      "Windows CE",
      "Symbian OS",
      "BlackBerry OS",
      "BlackBerry Tablet OS",
      "Firefox OS",
      "Brew MP",
      "webOS",
      "Bada",
      "Kindle",
      "Maemo"
    };
    private static readonly HashSet<string> s_MobileBrowsers = new HashSet<string>
    {
      "Android",
      "Firefox Mobile",
      "Opera Mobile",
      "Opera Mini",
      "Mobile Safari",
      "Amazon Silk",
      "webOS Browser",
      "MicroB",
      "Ovi Browser",
      "NetFront",
      "NetFront NX",
      "Chrome Mobile",
      "Chrome Mobile iOS",
      "UC Browser",
      "Tizen Browser",
      "Baidu Explorer",
      "QQ Browser Mini",
      "QQ Browser Mobile",
      "IE Mobile",
      "Polaris",
      "ONE Browser",
      "iBrowser Mini",
      "Nokia Services (WAP) Browser",
      "Nokia Browser",
      "Nokia OSS Browser",
      "BlackBerry WebKit",
      "BlackBerry", "Palm",
      "Palm Blazer",
      "Palm Pre",
      "Teleca Browser",
      "SEMC-Browser",
      "PlayStation Portable",
      "Nokia",
      "Maemo Browser",
      "Obigo",
      "Bolt",
      "Iris",
      "UP.Browser",
      "Minimo",
      "Bunjaloo",
      "Jasmine",
      "Dolfin",
      "Polaris",
      "Skyfire"
    };
    private static readonly HashSet<string> s_MobileDevices = new HashSet<string>
    {
      "BlackBerry",
      "MI PAD",
      "iPhone",
      "iPad",
      "iPod",
      "Kindle",
      "Kindle Fire",
      "Nokia",
      "Lumia",
      "Palm",
      "DoCoMo",
      "HP TouchPad",
      "Xoom",
      "Motorola",
      "Generic Feature Phone",
      "Generic Smartphone"
    };
    #endregion
    private readonly HttpContextBase _httpContext;
    private string _rawValue;
    private UserAgentInfo _userAgent;
    private DeviceInfo _device;
    private OSInfo _os;
    private bool? _isBot;
    private bool? _isMobileDevice;
    private bool? _isTablet;
    private bool? _isPdfConverter;
    static UAParserUserAgent()
    {
      s_uap = uap.Parser.GetDefault();
    }
    public UAParserUserAgent(HttpContextBase httpContext)
    {
      this._httpContext = httpContext;
    }
    public string RawValue
    {
      get
      {
        if (_rawValue == null)
        {
          if (_httpContext.Request != null)
          {
            _rawValue = _httpContext.Request.UserAgent.ToString();
          }
          else
          {
            _rawValue = "";
          }
        }
        return _rawValue;
      }
      // for (unit) test purpose
      set
      {
        _rawValue = value;
        _userAgent = null;
        _device = null;
        _os = null;
        _isBot = null;
        _isMobileDevice = null;
        _isTablet = null;
        _isPdfConverter = null;
      }
    }
    public virtual UserAgentInfo UserAgent
    {
      get
      {
        if (_userAgent == null)
        {
          var tmp = s_uap.ParseUserAgent(this.RawValue);
          _userAgent = new UserAgentInfo(tmp.Family, tmp.Major, tmp.Minor, tmp.Patch);
        }
        return _userAgent;
      }
    }
    public virtual DeviceInfo Device
    {
      get
      {
        if (_device == null)
        {
          var tmp = s_uap.ParseDevice(this.RawValue);
          _device = new DeviceInfo(tmp.Family, tmp.IsSpider);
        }
        return _device;
      }
    }
    public virtual OSInfo OS
    {
      get
      {
        if (_os == null)
        {
          var tmp = s_uap.ParseOS(this.RawValue);
          _os = new OSInfo(tmp.Family, tmp.Major, tmp.Minor, tmp.Patch, tmp.PatchMinor);
        }
        return _os;
      }
    }
    public virtual bool IsBot
    {
      get
      {
        if (!_isBot.HasValue)
        {
          _isBot = _httpContext.Request.Browser.Crawler || this.Device.IsBot;
        }
        return _isBot.Value;
      }
    }
    public virtual bool IsMobileDevice
    {
      get
      {
        if (!_isMobileDevice.HasValue)
        {
          _isMobileDevice =
            s_MobileOS.Contains(this.OS.Family) ||
            s_MobileBrowsers.Contains(this.UserAgent.Family) ||
            s_MobileDevices.Contains(this.Device.Family);
        }
        return _isMobileDevice.Value;
      }
    }
    public virtual bool IsTablet
    {
      get
      {
        if (!_isTablet.HasValue)
        {
          _isTablet =
            Regex.IsMatch(this.Device.Family, "iPad|Kindle Fire|Nexus 10|Xoom|Transformer|MI PAD|IdeaTab", RegexOptions.CultureInvariant) ||
            this.OS.Family == "BlackBerry Tablet OS";
        }
        return _isTablet.Value;
      }
    }
    public virtual bool IsPdfConverter
    {
      get
      {
        if (!_isPdfConverter.HasValue)
        {
          _isPdfConverter = s_pdfConverterPattern.IsMatch(this.RawValue);
        }
        return _isPdfConverter.Value;
      }
    }
}
public sealed class DeviceInfo
{
    public DeviceInfo(string family, bool isBot)
    {
      this.Family = family;
      this.IsBot = isBot;
    }
    public override string ToString()
    {
      return this.Family;
    }
    public string Family { get; private set; }
    public bool IsBot { get; private set; }
}
public sealed class OSInfo
{
    public OSInfo(string family, string major, string minor, string patch, string patchMinor)
    {
      this.Family = family;
      this.Major = major;
      this.Minor = minor;
      this.Patch = patch;
      this.PatchMinor = patchMinor;
    }
    public override string ToString()
    {
      var str = VersionString.Format(Major, Minor, Patch, PatchMinor);
      return (this.Family + (!string.IsNullOrEmpty(str) ? (" " + str) : null));
    }
    public string Family { get; private set; }
    public string Major { get; private set; }
    public string Minor { get; private set; }
    public string Patch { get; private set; }
    public string PatchMinor { get; private set; }
    private static string FormatVersionString(params string[] parts)
    {
      return string.Join(".", (from v in parts
                   where !string.IsNullOrEmpty(v)
                   select v).ToArray<string>());
    }
}
public sealed class UserAgentInfo
{
    public UserAgentInfo(string family, string major, string minor, string patch)
    {
      this.Family = family;
      this.Major = major;
      this.Minor = minor;
      this.Patch = patch;
    }
    public override string ToString()
    {
      var str = VersionString.Format(Major, Minor, Patch);
      return (this.Family + (!string.IsNullOrEmpty(str) ? (" " + str) : null));
    }
    public string Family { get; private set; }
    public string Major { get; private set; }
    public string Minor { get; private set; }
    public string Patch { get; private set; }
}
internal static class VersionString
{
    public static string Format(params string[] parts)
    {
      return string.Join(".", (from v in parts
                   where !string.IsNullOrEmpty(v)
                   select v).ToArray<string>());
    }
}

控制器中代码:

UAParserUserAgent userAgent = new UAParserUserAgent(this.HttpContext);
dto.OSInfo = userAgent.OS.ToString();
dto.Device = userAgent.Device.ToString() != "Other" ? userAgent.Device.ToString() : "电脑";
dto.Agent = userAgent.UserAgent.ToString();
dto.RawValue = userAgent.RawValue.ToString();
//if (userAgent.IsMobileDevice)
//{
//  Debug.WriteLine("这是一个手机");
//  ViewBag.MobilePc = "手机";
//}
//else if (userAgent.IsTablet)
//{
//  ViewBag.MobilePc = "平板";
//  Debug.WriteLine("这是一个平板");
//}
//else
//{
//  ViewBag.MobilePc = "普通电脑";
//  Debug.WriteLine("这是一个普通电脑");
//}

更多关于C#相关内容感兴趣的读者可查看本站专题:《C#程序设计之线程使用技巧总结》、《WinForm控件用法总结》、《C#中XML文件操作技巧汇总》、《C#常见控件用法教程》、《C#数据结构与算法教程》、《C#数组操作技巧总结》及《C#面向对象程序设计入门教程》

希望本文所述对大家C#程序设计有所帮助。

(0)

相关推荐

  • C#用Activex实现Web客户端读取RFID功能的代码

    由于要在Web项目中采用RFID读取功能,所以有必要开发Activex,一般情况下开发Activex都采用VC,VB等,但对这两块不是很熟悉,所以采用C#编写Activex的方式实现. 本文方法参考网络 1.编写WindowsFromControls 2.发布WindowsFormControls为Activex 3.在web中使用该Activex 首先编写windows控件 如何编写不再详述(注意一个地方,GUID自己用vs工具生成一个,下面会用到.我的0CBD6597-3953-4B88-8

  • asp.net(C#)中给控件添加客户端js事件的方法

    放在服务器端,也可以用ajax来实现,不刷页面.但我觉得有更直接更简单方法,用一个js事件是可以实现的. 但,DropDownList不偈Button等控件提供了一些像"OnClientClick"前台事件,只有服务端事件. 想到,所有C#页面代码,最终都是生成HTML,js事件也是最终运在浏览器中,以Html为基础的.服务端控件最终生成的HTML控件有什么js事件,我们应该就能在aspx中给它添加相应的事件. DropDownList 生成的Htm是元素<Select>是

  • 客户端实现蓝牙接收(C#)知识总结

    在实现蓝牙接收时,网上的资料很多,使用起来也很简单,但是我觉得还是有必要把这些知识总结下来.蓝牙开发需要用到一个第三方的库InTheHand.Net.Personal.dll,其中关键的两个类是 BluetoothClient 和 BluetoothListener,首先开启一个子线程来不断的接收数据,使用很简单,直接上代码: 复制代码 代码如下: using InTheHand.Net.Sockets; using System.Threading; public MainWindow() {

  • asp.net(c#)限制用户输入规定的字符和数字的代码

    一下是这个代码: 只允许 用户名输入:用户名称的开头,必须为0~9.a~z或A~Z ! 复制代码 代码如下: protected void Button3_Click(object sender, EventArgs e) { int error_count = 0; //用于识别用户名的合法性 string str = TextBox1.Text.Trim(); if (str == string.Empty) { Response.Write("用户名称不能为空!"); retur

  • C#实现支持断点续传多线程下载客户端工具类

    复制代码 代码如下: /* .Net/C#: 实现支持断点续传多线程下载的 Http Web 客户端工具类 (C# DIY HttpWebClient) * Reflector 了一下 System.Net.WebClient ,改写或增加了若干: * DownLoad.Upload 相关方法! * DownLoad 相关改动较大! * 增加了 DataReceive.ExceptionOccurrs 事件! * 了解服务器端与客户端交互的 HTTP 协议参阅: * 使文件下载的自定义连接支持

  • C#编程获取客户端计算机硬件及系统信息功能示例

    本文实例讲述了C#编程获取客户端计算机硬件及系统信息功能.分享给大家供大家参考,具体如下: 这里使用C#获取客户端计算机硬件及系统信息 ,包括CPU.硬盘.IP.MAC地址.操作系统等. 1.项目引用System.Management库. 2.创建HardwareHandler.cs类文件 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Manag

  • C#聊天程序服务端与客户端完整实例代码

    本文所述为基于C#实现的多人聊天程序服务端与客户端完整代码.本实例省略了结构定义部分,服务端主要是逻辑处理部分代码,因此使用时需要完善一些窗体按钮之类的. 先看服务端代码如下: using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Net; using

  • 在C#中对TCP客户端的状态封装详解

    TCP客户端连接TCP服务器端有几种应用状态:1.与服务器的连接已建立2.与服务器的连接已断开3.与服务器的连接发生异常 应用程序可按需求合理处理这些逻辑,比如:1.连接断开后自动重连2.连接断开后选择备用地址重连3.所有状态变化上报告警本文描述的TcpClient实现了状态变化的事件通知机制. 复制代码 代码如下: /// <summary>   /// 异步TCP客户端   /// </summary>   public class AsyncTcpClient : IDisp

  • C#获取客户端相关信息实例总结

    本文实例讲述了C#获取客户端相关信息的方法.分享给大家供大家参考.具体如下: [本机IP地址] 第一种方法: IPHostEntry hostentry = Dns.Resolve(Dns.GetHostName()); IPAddress address=hostentry.AddressList[0]; 第二种方法: 复制代码 代码如下: Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(); [判断当前用户是否连网] PingReply

  • c#多线程网络聊天程序代码分享(服务器端和客户端)

    XuLIeHua类库 复制代码 代码如下: using System;using System.Collections;  using System.Collections.Generic;using System.Threading;  using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Binary;using System.Text;using System.IO;using Sy

  • 获取客户端IP地址c#/vb.net各自实现代码

    公司的域环境内,程序要求获取客户端的IP地址,分部程序码分享于此. C#: VB.NET:

随机推荐