C# MVC登录判断状态


  public class AuthenAdminAttribute:FilterAttribute,IAuthorizationFilter
    {
       
        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
            //这个方法是在Action执行之后调用
        }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            //这个方法是在Action执行之前调用
            var user = filterContext.HttpContext.Session["userName"];
            if (user == null)
            {
                //filterConetext.HttpContext.Response.Redirect("/Login/index");
                var url = new UrlHelper(filterContext.RequestContext);
                var urls = url.Action("Index", "Login");
                filterContext.Result = new RedirectResult(urls);
            }
        }
    }

  在需要使用做登录状态判断的地方添加[Autenadmin]放在类前面表示整个控制器的每个Action都需要验证

     单独放在Action之前表示只有该Action需要验证  

    [AuthenAdmin]
    public class HelloController : Controller
    {
        // GET: Hello
        public ActionResult Index()
        {
            return View();
        }
        public string welcome(string name,int id=1){

            return HttpUtility.HtmlEncode("hello "+name+":"+id);
        }
    }
  • 在Controller类中方法访问级别为public的方法,就是行为(Action).
  • 如果不希望Controller类中的方法成为Action(可以在地址栏中被访问),有两种实现方式:
  1. 将方法的访问级别设置为private
  2. 在方法上添加特性标记[NonAction]

借鉴: http://www.lanhusoft.com/Article/73.html

方法二:
public class BaseController : Controller
    {

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            if (HttpContext != null)
            {
                if (HttpContext.Session["userName"] != null)
                {


                }
                else
                {
                    filterContext.Result = new RedirectResult("/Login/Index");
                }
            }
            base.OnActionExecuting(filterContext);
        }
    }

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM