在WEB项目中建立 类:
public class LoginFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//HttpContext.Current.Response.Write("OnActionExecuting:正要准备执行Action的时候但还未执行时执行<br />");
if (HttpContext.Current.Session"admin" == null)
{
//HttpContext.Current.Response.Write("js代码");
//HttpContext.Current.Response.End();
//return;
var context = new ContentResult();
context.Content = "<script>alert('请重新登录!');location.href='/Login/Index'</script>";
filterContext.Result = context;
//HttpContext.Current.Response.End();
//return;
var context = new ContentResult();
context.Content = "<script>alert('请重新登录!');location.href='/Login/Index'</script>";
filterContext.Result = context;
}
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
//HttpContext.Current.Response.Write("OnActionExecuted:Action执行时但还未返回结果时执行<br />");
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
// HttpContext.Current.Response.Write("OnResultExecuting:OnResultExecuting也和OnActionExecuted一样,但前者是在后者执行完后才执行<br />");
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
// HttpContext.Current.Response.Write("OnResultExecuted:是Action执行完后将要返回ActionResult的时候执行<br />");
}
}
使用方法,直接在控制里方法外面写,如:
[LoginFilter]
public ActionResult Add()
{
Model.Userinfo loginuser = base.GetLoginUser();
Model.Product pro = new Model.Product() { userid = loginuser.id, username = loginuser.username };
return View(pro);
}