一、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) == 0 || String.IsNullOrEmpty(CustomerIP)) { return System.Web.HttpContext.Current.Request.UserHostAddress; } return CustomerIP; } catch { } return userIP; }