现在我们开发的很多web应用都要支持手机等移动设备。为了让手机用户能有更加好的用户体验,我们经常为手机设备专门准备一套前端的页面。这样当用户使用普通电脑来访问的时候,我们的应用就向用户展示普通电脑的页面。当用户使用手机等移动设备来访问我们的系统的时候,我们就向用户展示手机设备的页 ...
现在我们开发的很多web应用都要支持手机等移动设备。为了让手机用户能有更加好的用户体验,我们经常为手机设备专门准备一套前端的页面。这样当用户使用普通电脑来访问的时候,我们的应用就向用户展示普通电脑的页面。当用户使用手机等移动设备来访问我们的系统的时候,我们就向用户展示手机设备的页面。但是这时候另一个问题出现了。如何判断用户在使用什么设备访问我们的应用?是使用手机还是普通电脑?
网上能查到的不同的实现方式不少。我在这里也介绍一个我们最近在项目中采用的方法。
我们使用的是UAParser。UAParser是一个开源的项目,主要的功能是实现对各种用户useragent的解析。现在已经有很多种编程语言的实现。C#只是其中的一种。
为了方便大家理解,我在这里把主要的步骤和代码都写出来。
1) 用vs2013新建一个get='_blank'>mvc的项目。
2) 使用nuget下载UAParser
3) 新建一个接口和实现它的类。
4) 代码
IUserAgent
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace UserDeviceDetectWebApplication.Service{ public interface IUserAgent { string RawValue { get; set; } UserAgentInfo UserAgent { get; } DeviceInfo Device { get; } OSInfo OS { get; } bool IsBot { get; } bool IsMobileDevice { get; } bool IsTablet { get; } //bool IsPdfConverter { get; } } 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>()); } }}
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:使用UAParser在C#MVC项目中如何判断用户是在用什么设备进行访问(手机,平板还是普通的电脑)
关键词:C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。