.NET/C#实现识别用户访问设备的方法
本文实例讲述了.NET/C#实现识别用户访问设备的方法。分享给大家供大家参考,具体如下:
一、需求
需要获取到用户访问网站时使用的设备,根据不同设备返回不同类型的渲染页面。
二、实现前准备
通过NuGet把UAParser程序包添加到项目中
三、实现
新建UAParseUserAgent类文件,在这个文件中进行实现。
实现代码如下:
publicclassUAParserUserAgent { privatereadonlystaticuap.Parsers_uap; privatestaticreadonlyRegexs_pdfConverterPattern=newRegex(@"wkhtmltopdf",RegexOptions.Compiled|RegexOptions.IgnoreCase|RegexOptions.CultureInvariant); #regionMobileUAs,OS&Devices privatestaticreadonlyHashSet<string>s_MobileOS=newHashSet<string> { "Android", "iOS", "WindowsMobile", "WindowsPhone", "WindowsCE", "SymbianOS", "BlackBerryOS", "BlackBerryTabletOS", "FirefoxOS", "BrewMP", "webOS", "Bada", "Kindle", "Maemo" }; privatestaticreadonlyHashSet<string>s_MobileBrowsers=newHashSet<string> { "Android", "FirefoxMobile", "OperaMobile", "OperaMini", "MobileSafari", "AmazonSilk", "webOSBrowser", "MicroB", "OviBrowser", "NetFront", "NetFrontNX", "ChromeMobile", "ChromeMobileiOS", "UCBrowser", "TizenBrowser", "BaiduExplorer", "QQBrowserMini", "QQBrowserMobile", "IEMobile", "Polaris", "ONEBrowser", "iBrowserMini", "NokiaServices(WAP)Browser", "NokiaBrowser", "NokiaOSSBrowser", "BlackBerryWebKit", "BlackBerry","Palm", "PalmBlazer", "PalmPre", "TelecaBrowser", "SEMC-Browser", "PlayStationPortable", "Nokia", "MaemoBrowser", "Obigo", "Bolt", "Iris", "UP.Browser", "Minimo", "Bunjaloo", "Jasmine", "Dolfin", "Polaris", "Skyfire" }; privatestaticreadonlyHashSet<string>s_MobileDevices=newHashSet<string> { "BlackBerry", "MIPAD", "iPhone", "iPad", "iPod", "Kindle", "KindleFire", "Nokia", "Lumia", "Palm", "DoCoMo", "HPTouchPad", "Xoom", "Motorola", "GenericFeaturePhone", "GenericSmartphone" }; #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(HttpContextBasehttpContext) { this._httpContext=httpContext; } publicstringRawValue { get { if(_rawValue==null) { if(_httpContext.Request!=null) { _rawValue=_httpContext.Request.UserAgent.ToString(); } else { _rawValue=""; } } return_rawValue; } //for(unit)testpurpose set { _rawValue=value; _userAgent=null; _device=null; _os=null; _isBot=null; _isMobileDevice=null; _isTablet=null; _isPdfConverter=null; } } publicvirtualUserAgentInfoUserAgent { get { if(_userAgent==null) { vartmp=s_uap.ParseUserAgent(this.RawValue); _userAgent=newUserAgentInfo(tmp.Family,tmp.Major,tmp.Minor,tmp.Patch); } return_userAgent; } } publicvirtualDeviceInfoDevice { get { if(_device==null) { vartmp=s_uap.ParseDevice(this.RawValue); _device=newDeviceInfo(tmp.Family,tmp.IsSpider); } return_device; } } publicvirtualOSInfoOS { get { if(_os==null) { vartmp=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|KindleFire|Nexus10|Xoom|Transformer|MIPAD|IdeaTab",RegexOptions.CultureInvariant)|| this.OS.Family=="BlackBerryTabletOS"; } 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() { varstr=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(".",(fromvinparts where!string.IsNullOrEmpty(v) selectv).ToArray<string>()); } } publicsealedclassUserAgentInfo { publicUserAgentInfo(stringfamily,stringmajor,stringminor,stringpatch) { this.Family=family; this.Major=major; this.Minor=minor; this.Patch=patch; } publicoverridestringToString() { varstr=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(".",(fromvinparts where!string.IsNullOrEmpty(v) selectv).ToArray<string>()); } }
控制器中代码:
UAParserUserAgentuserAgent=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="手机"; //} //elseif(userAgent.IsTablet) //{ //ViewBag.MobilePc="平板"; //Debug.WriteLine("这是一个平板"); //} //else //{ //ViewBag.MobilePc="普通电脑"; //Debug.WriteLine("这是一个普通电脑"); //}
更多关于C#相关内容感兴趣的读者可查看本站专题:《C#程序设计之线程使用技巧总结》、《WinForm控件用法总结》、《C#中XML文件操作技巧汇总》、《C#常见控件用法教程》、《C#数据结构与算法教程》、《C#数组操作技巧总结》及《C#面向对象程序设计入门教程》
希望本文所述对大家C#程序设计有所帮助。