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

作者:袖梨 2022-06-25

一、需求

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

二、实现前准备

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

三、实现

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

实现代码如下:

 

 代码如下复制代码

publicclassUAParserUserAgent

{

    privatereadonlystaticuap.Parser s_uap;

    privatestaticreadonlyRegex s_pdfConverterPattern =newRegex(@"wkhtmltopdf", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

    # region Mobile UAs, OS & Devices

    privatestaticreadonlyHashSets_MobileOS =newHashSet

    {

      "Android",

      "iOS",

      "Windows Mobile",

      "Windows Phone",

      "Windows CE",

      "Symbian OS",

      "BlackBerry OS",

      "BlackBerry Tablet OS",

      "Firefox OS",

      "Brew MP",

      "webOS",

      "Bada",

      "Kindle",

      "Maemo"

    };

    privatestaticreadonlyHashSets_MobileBrowsers =newHashSet

    {

      "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"

    };

    privatestaticreadonlyHashSets_MobileDevices =newHashSet

    {

      "BlackBerry",

      "MI PAD",

      "iPhone",

      "iPad",

      "iPod",

      "Kindle",

      "Kindle Fire",

      "Nokia",

      "Lumia",

      "Palm",

      "DoCoMo",

      "HP TouchPad",

      "Xoom",

      "Motorola",

      "Generic Feature Phone",

      "Generic Smartphone"

    };

    #endregion

    privatereadonlyHttpContextBase _httpContext;

    privatestring_rawValue;

    privateUserAgentInfo _userAgent;

    privateDeviceInfo _device;

    privateOSInfo _os;

    privatebool? _isBot;

    privatebool? _isMobileDevice;

    privatebool? _isTablet;

    privatebool? _isPdfConverter;

    staticUAParserUserAgent()

    {

      s_uap = uap.Parser.GetDefault();

    }

    publicUAParserUserAgent(HttpContextBase httpContext)

    {

      this._httpContext = httpContext;

    }

    publicstringRawValue

    {

      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;

      }

    }

    publicvirtualUserAgentInfo UserAgent

    {

      get

      {

        if(_userAgent ==null)

        {

          var tmp = s_uap.ParseUserAgent(this.RawValue);

          _userAgent =newUserAgentInfo(tmp.Family, tmp.Major, tmp.Minor, tmp.Patch);

        }

        return_userAgent;

      }

    }

    publicvirtualDeviceInfo Device

    {

      get

      {

        if(_device ==null)

        {

          var tmp = s_uap.ParseDevice(this.RawValue);

          _device =newDeviceInfo(tmp.Family, tmp.IsSpider);

        }

        return_device;

      }

    }

    publicvirtualOSInfo OS

    {

      get

      {

        if(_os ==null)

        {

          var tmp = s_uap.ParseOS(this.RawValue);

          _os =newOSInfo(tmp.Family, tmp.Major, tmp.Minor, tmp.Patch, tmp.PatchMinor);

        }

        return_os;

      }

    }

    publicvirtualboolIsBot

    {

      get

      {

        if(!_isBot.HasValue)

        {

          _isBot = _httpContext.Request.Browser.Crawler ||this.Device.IsBot;

        }

        return_isBot.Value;

      }

    }

    publicvirtualboolIsMobileDevice

    {

      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;

      }

    }

    publicvirtualboolIsTablet

    {

      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;

      }

    }

    publicvirtualboolIsPdfConverter

    {

      get

      {

        if(!_isPdfConverter.HasValue)

        {

          _isPdfConverter = s_pdfConverterPattern.IsMatch(this.RawValue);

        }

        return_isPdfConverter.Value;

      }

    }

}

publicsealedclassDeviceInfo

{

    publicDeviceInfo(stringfamily,boolisBot)

    {

      this.Family = family;

      this.IsBot = isBot;

    }

    publicoverridestringToString()

    {

      returnthis.Family;

    }

    publicstringFamily {get;privateset; }

    publicboolIsBot {get;privateset; }

}

publicsealedclassOSInfo

{

    publicOSInfo(stringfamily,stringmajor,stringminor,stringpatch,stringpatchMinor)

    {

      this.Family = family;

      this.Major = major;

      this.Minor = minor;

      this.Patch = patch;

      this.PatchMinor = patchMinor;

    }

    publicoverridestringToString()

    {

      var str = VersionString.Format(Major, Minor, Patch, PatchMinor);

      return(this.Family + (!string.IsNullOrEmpty(str) ? (" "+ str) :null));

    }

    publicstringFamily {get;privateset; }

    publicstringMajor {get;privateset; }

    publicstringMinor {get;privateset; }

    publicstringPatch {get;privateset; }

    publicstringPatchMinor {get;privateset; }

    privatestaticstringFormatVersionString(paramsstring[] parts)

    {

      returnstring.Join(".", (from vinparts

                   where !string.IsNullOrEmpty(v)

                   select v).ToArray());

    }

}

publicsealedclassUserAgentInfo

{

    publicUserAgentInfo(stringfamily,stringmajor,stringminor,stringpatch)

    {

      this.Family = family;

      this.Major = major;

      this.Minor = minor;

      this.Patch = patch;

    }

    publicoverridestringToString()

    {

      var str = VersionString.Format(Major, Minor, Patch);

      return(this.Family + (!string.IsNullOrEmpty(str) ? (" "+ str) :null));

    }

    publicstringFamily {get;privateset; }

    publicstringMajor {get;privateset; }

    publicstringMinor {get;privateset; }

    publicstringPatch {get;privateset; }

}

internalstaticclassVersionString

{

    publicstaticstringFormat(paramsstring[] parts)

    {

      returnstring.Join(".", (from vinparts

                   where !string.IsNullOrEmpty(v)

                   select v).ToArray());

    }

}

控制器中代码:

UAParserUserAgent userAgent =newUAParserUserAgent(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("这是一个普通电脑");

//}

 

相关文章

精彩推荐