1.实例一
/// <summary> /// 需要用户登陆的 action,执行提前验证 /// </summary> public class LoginFilterAttribute : FilterAttribute, IActionFilter { void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext) { } /// <summary> /// 执行action 前验证 用户是否登陆,如果没有登陆返回字符串体质 /// </summary> /// <param name="filterContext"></param> void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) { // throw new NotImplementedException(); //1.判断 if (A_UserHelper.IsLogin() == false) { ContentResult result = new ContentResult(); result.Content = "亲,还没有登陆,请先登录"; filterContext.Result = result; } } }
2.实例二
public class LoginGoAttribute : FilterAttribute, IActionFilter { void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext) { //throw new NotImplementedException(); } /// <summary> /// 执行action 之前 验证用户是否登陆,如果没有登陆返回登陆页面 /// </summary> /// <param name="filterContext"></param> void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) { //throw new NotImplementedException(); if (A_UserHelper.IsLogin() == false) { //不跳转在当前地址返回登陆页------ //RouteData route = filterContext.RouteData; //route.Values["controller"] = "user"; //route.Values["action"] = "login"; //IController IController = new UserController(); //HttpContextBase context = filterContext.HttpContext; //IController.Execute(new RequestContext(context, route)); //filterContext.Result = new ContentResult(); //重定向到登陆页--------不推荐使用,因为当前action还是会执行 //HttpContextBase context = filterContext.HttpContext; //context.Response.Redirect(SiteUrl.GetLogin(),true); //context.Response.End(); //filterContext.ActionDescriptor = null; //临时重定向到登陆页 HttpRequestBase req = filterContext.HttpContext.Request; string url = SiteUrl.GetLogin() + "?redirecturl=" + req.Url.AbsoluteUri; RedirectResult result = new RedirectResult(url, false); filterContext.Result = result; //此方法 失败 //HttpContextBase context = filterContext.HttpContext; //UserController userC = new UserController(); //userC.ControllerContext = new ControllerContext(); //userC.ControllerContext.RouteData.DataTokens["controller"] = "user"; //userC.ControllerContext.RouteData.Values["area"] = ""; //ContentResult content = new ContentResult(); //content.Content = ViewHelper.RenderViewToString(userC, "login", null); ; //filterContext.Result = content; } } }
更多: