我是 ASP.net MVC4 的新手,我想做一个可以记录系统登录时间和系统注销时间以及 IP 地址的程序。
提前致谢....
要记录客户端 IP 地址,请使用
HttpContext.Request.UserHostAddress //In Controller
or
HttpContext.Current.Request.UserHostAddress// In Classes
记录登录和注销时间。
创建一个自定义操作过滤器类并记录日期时间,如下所示。
[CustomFilter(CurrentAction="Login")]
public ActionResult Login()
{
...
}
[CustomFilter(CurrentAction="Logout")]
public ActionResult Logout()
{
...
}
public class CustomFilter : ActionFilterAttribute
{
String CurrentAction {get; set;}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
// TODO: Add your action filter's tasks here
MyDBEntities storeDB = new MyDBEntities ();
if(CurrentAction.Equals("Login"))
{
LoginDetail log = new LoginDetail ()
{
LoginTime= DateTime.Now,
IP = filterContext.HttpContext.Request.UserHostAddress
};
storeDB.LoginDetails.Add(log);
}
else if(CurrentAction.Equals("Logout"))
{
LoginDetail log = new LoginDetail ()
{
LogoutTime= DateTime.Now,
IP = filterContext.HttpContext.Request.UserHostAddress
};
storeDB.LoginDetails.Add(log);
}
storeDB.SaveChanges();
this.OnActionExecuting(filterContext);
}
}