稍微研究了一下,服务器如何获取用户的信息做了一个整理。
cs代码 通过反射来访问类的实例属性和属性值
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; using System.Reflection; using System.Text.RegularExpressions; namespace Whoru { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { System.Web.HttpBrowserCapabilities bCaps; // 请求者的浏览器信息 bCaps = Request.Browser; // 获取bCaps对象的类型 Type type = bCaps.GetType(); object obj = Activator.CreateInstance(type); // 属性信息数组 PropertyInfo[] props = type.GetProperties(); string str = string.Empty; // 遍历实例的所有属性,及属性值 foreach (PropertyInfo pi in props) { // 属性名 string name = pi.Name; try { str += string.Format("{0}:{1}", pi.Name, pi.GetValue(bCaps, null).ToString()); str += "<br>"; } catch (Exception ex) { //Response.Write("error:"+ex.Message); str += "<br>"; } } // 为了加强准确性,防止支持wap的浏览器如opera,加入操作系统验证。openwave|后为pc操作系统 // Chrome浏览器有点捣蛋,它的agent信息里会包括Mozilla,Chrome,Safari等信息,所以必要时要做一些特殊的判断 string osPat = "mozilla|m3gate|winwap|openwave|Windows NT|Windows 3.1|95|Blackcomb|98|ME|X Window|Longhorn|ubuntu|AIX|Linux|AmigaOS|BEOS|HP-UX|OpenBSD|FreeBSD|NetBSD|OS/2|OSF1|SUN"; string osMob = "Android|iPhone|iPod|iPad|Windows Phone|MQQBrowser"; string uAgent = Request.ServerVariables["HTTP_USER_AGENT"]; Regex reg = new Regex(osPat); Regex regMob = new Regex(osMob); if (reg.IsMatch(uAgent)) { str += "电脑访问"; } else if (regMob.IsMatch(uAgent)) { str += "手机访问"; } else { str += "未知的设备"; } str += "<br/>" + uAgent; divContent.InnerHtml = str; } } }
html代码
把div定义为服务器控件,然后在后台把信息输出。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Whoru._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> <script language="javascript"> function setBrowser() { var browser="unknown"; var userAgent = navigator.userAgent.toLowerCase(); if (userAgent.indexOf("chrome") > -1) browser="Opera"; else if (userAgent.indexOf("konqueror") > -1) browser="Konqueror"; else if (userAgent.indexOf("firefox") > -1) browser="Firefox"; else if (userAgent.indexOf("netscape") > -1) browser="Netscape"; else if (userAgent.indexOf("msie") > -1) browser="Internet Explorer"; else if (userAgent.indexOf("opera") > -1) browser="Chrome"; else if (userAgent.indexOf("safari") > -1) browser="Safari"; var brDiv=document.getElementById("browser"); brDiv.innerHTML=userAgent+"<b>" + browser + "</b>"; } window.onload=setBrowser; </script> </head> <body> <form id="form1" runat="server"> You are using: <div id="browser"></div> <div id="divContent" runat="server"> </div> </form> </body> </html>