一、Web端开发时,用户登录后往往会通过Session来保存用户信息,Session存放在服务器,当用户长时间不操作的时候,我们会希望服务器保存的Session过期,这个时候,因为Session中的用户信息取不到了,就需要用户重新登录,重新保存Session。
Web在登出的时候可以通过HttpSession.Invalidate()//使所有Session作废
Asp.net MVC提供了过滤器,让我们可以很方便的控制访问Action时要处理的事情,针对Session过期后页面跳转,我们可以封装一下Controller的OnActionExecuting方法作为基Controller,如下:
public class BaseController : Controller
{
protected User UserInfo
{
set
{
Session["UserInfo"] = value;
} get
{
if (Session["UserInfo"] == null)
{
return null;
}
else
{
return (User)Session["UserInfo"];
}
}
} protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
#region Session判断
if (UserInfo==null && !filterContext.ActionDescriptor.ActionName.Contains("Login"))
{
filterContext.Result = new RedirectResult("/Home/Login");
return;
}
#endregion base.OnActionExecuting(filterContext);
}
}
但是,这儿的new RedirectResult("/Home/Login");只是把Action的返回指向为了/Home/Login,如果用户操作的页面是嵌套在iframe中,这个时候,只是iframe的指向改变了,问不是地址栏的指向改变了,针对这种情况,可在前台页面/Home/Login做限制,如下:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>系统-登录</title>
<link href="/Content/login.css" rel="stylesheet" /> <script type="text/javascript">
$(function () {
//判断一下当前是不是做顶层,如果不是,则做一下顶层页面重定向
if (window != top) {
top.location.href = location.href;
}
});
</script>
</head>
<body>
</body>
</html>
参照如下:http://blog.csdn.net/u012251421/article/details/50332513
二、在asp.net mvc我们在记录日志的时候,经常会考虑记录访问者的ip地址,即客户端的ip地址,以下是一个参考的获取ip地址的方式:
/// <summary>
/// 获取web客户端ip
/// </summary>
/// <returns></returns>
public static string GetWebClientIp()
{ string userIP = "未获取用户IP"; try
{
if (System.Web.HttpContext.Current == null
|| System.Web.HttpContext.Current.Request == null
|| System.Web.HttpContext.Current.Request.ServerVariables == null)
{
return "";
} string CustomerIP = ""; //CDN加速后取到的IP simone 090805
CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
if (!string.IsNullOrEmpty(CustomerIP))
{
return CustomerIP;
} CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (!String.IsNullOrEmpty(CustomerIP))
{
return CustomerIP;
} if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
{
CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (CustomerIP == null)
{
CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
}
else
{
CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
} if (string.Compare(CustomerIP, "unknown", true) == || String.IsNullOrEmpty(CustomerIP))
{
return System.Web.HttpContext.Current.Request.UserHostAddress;
}
return CustomerIP;
}
catch { } return userIP; }