MVC项目中时,写一个基类来判断session是否已过期然后跳转到指定的错误页面或者登陆界面,然后让所有的页面都继承这个基类,这种方法是并不会起作用的。所以我百度了一下,进行了总结。
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
namespace EHR.Controllers
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class AuthenticatedFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Session["key"] == null || filterContext.HttpContext.Session["key"] == "")
{
GoUrl(filterContext);
}
}
private static void GoUrl(ActionExecutingContext filterContext)
{
filterContext.Result = new RedirectToRouteResult("Default", new System.Web.Routing.RouteValueDictionary(new
{
action = "Index",
controller = "Login"
}));
}
}
}
然后在每个方法前面调用该方法:
[AuthenticatedFilter]
public ActionResult otherInAffair(string parentId, string currentId)
{
return View();
}