C# 获取域用户信息并统计域用户访问过的页面
时间:2011-05-11 来源:忆起
最近,公司让做个网站,因为是内网的,所以为了方便,采用域用户,而不用重新注册。
1. 下面是根据WindowsPrincipal获取当前域用户的用户名和域
1 using System;
2 using System.Collections.Generic;
3 using System.Web;
4 using System.Security.Principal;
5 using System.Threading;
6
7 public class MyPrincipal
8 {
9 WindowsPrincipal wp = (WindowsPrincipal)Thread.CurrentPrincipal;
10
11 /// <summary>
12 /// 获取域用户名
13 /// </summary>
14 public string UserName {
15 get {
16 string[] wpArray = wp.Identity.Name.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
17 return wpArray.Length>0?wpArray[1]:"";
18 }
19 }
20
21 /// <summary>
22 /// 获取域名
23 /// </summary>
24 public string UserDomain
25 {
26 get
27 {
28 string[] wpArray = wp.Identity.Name.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
29 return wpArray.Length > 0 ? wpArray[0] : "";
30 }
31 }
32 }
2. 因为要统计域用户的访问记录,并且网站页面很多,不可能每个页面都加上统计代码,这里有两个方法解决(限于个人水平,只想到两个方法,应该还有其它方法):
a.页面基类的方式,即新建一个页面基类(BasePage),继承page类,并重写OnInit方法,将统计代码写入,然后其它页面继承BasePage就可以了。
b.HttpModule方式,新建一个asp.net 模块,将统计代码写入AcquireRequestState事件中,具体代码如下:
View Code1 public class Counter : IHttpModule注:因为要用到session,所以统计代码写在context_AcquireRequestState事件中,因为在此之前HttpRequest还未交给HttpHandler,session还不存在。并且如果用太靠前的事件,如:BeginRequest等,
2 {
3 /// <summary>
4 /// You will need to configure this module in the web.config file of your
5 /// web and register it with IIS before being able to use it. For more information
6 /// see the following link: http://go.microsoft.com/?linkid=8101007
7 /// </summary>
8 #region IHttpModule Members
9
10 public void Dispose()
11 {
12 //clean-up code here.
13 }
14
15 public void Init(HttpApplication context)
16 {
17 context.AcquireRequestState += new EventHandler(context_AcquireRequestState);
18 }
19
20 void context_AcquireRequestState(object sender, EventArgs e)
21 {
22 HttpApplication application = (HttpApplication)sender;
23 HttpContext context = application.Context;
24
25 //即上面获取域用户的类
26 MyPrincipal mp = new MyPrincipal();
27
28 if (mp.UserName!="")
29 {
30
31 try
32 {
33 Model model = new Model ();
34 model.UserName = mp.UserName;
35 model.UserDomain = mp.UserDomain;
36 model.Page = context.Request.Url.ToString();
37 model.SessionID = context.Session.SessionID;
38 model.CreateOn = DateTime.Now.ToString("yyyy-MM-dd");
39
40 Service service = new Service();
41 if (!service.Exists(model))
42 {
43 service.Insert(model);
44 }
45 }
46 catch (Exception ex)
47 {
48 service.Log(ex.Message);
49 }
50 }
51 }
52 #endregion
53
54 }
WindowsPrincipal wp = (WindowsPrincipal)Thread.CurrentPrincipal; 此处会报错,可能是因为此处CurrentPrincipal还不存在吧。
水平有限,欢迎大家拍砖指正。
相关阅读 更多 +