• MVC3中使用AuthorizeAttribute特性来完成登陆权限的验证


    以前判断用户是否登录,判断用户Session是否为空,一般会在这个页面写使用:

    if (HttpContext.Session.IsNewSession)
    {
    //todo Login
    }

    每个需要验证的页面这样验证,之后.net出现Attribute之后,如果判断某个页面的访问是否登录或者其他权限,只需要:

    [UserAuthentication(UserToUrlEnum = UserToUrlEnum.Login)]
    public ActionResult RegisterRedirect()
    {
    // code
    }
    public enum UserToUrlEnum
    {
    /// <summary>
    /// 登录
    /// </summary>
    Login,
    /// <summary>
    /// 注册
    /// </summary>
    Register,
    /// <summary>
    /// 认证
    /// </summary>
    Certificate,
    }
    public class UserAuthentication : AuthorizeAttribute
    {
    const string DOMAIN = "http://www.test.com";
    public UserToUrlEnum UserToUrlEnum { get; set; }
    /// <summary>
    /// 构造函数
    /// </summary>
    public UserAuthentication()
    {
    this.UserToUrlEnum = UserToUrlEnum.Login;
    }
    /// <summary>
    /// 执行前验证
    /// </summary>
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
    if (filterContext.HttpContext.Session.IsNewSession && !ClientHelper.Current.HasUser)
    {
    switch (this.UserToUrlEnum)
    {
    case UserToUrlEnum.Login:
    {
    VCommons.Http.CookieHelper.Write("return_page",

    HttpContext.Current.Request.Url.ToString());

    HttpContext.Current.Response.Redirect(DOMAIN +
    "/Register/Login", true);
    }
    break;
    case UserToUrlEnum.Register:
    {
    filterContext.HttpContext.Response.Redirect(DOMAIN +

    "/Register/Register", true);

    }
    break;
    }
    }
    else if (this.UserToUrlEnum == UserToUrlEnum.Certificate)
    {
    filterContext.HttpContext.Response.Redirect(DOMAIN + "/Register/Certificate");
    }

    }

    }

  • 相关阅读:
    Property总结
    静态类和 关于什么时候使用“静态方法”
    最简单的MVVM结构(学习)
    依赖属性和附加属性1(转载)
    Nested & Access modifiers
    Template methord
    WPF 绑定及惯用法(一) 转载自loveis715
    关于Property赋值
    Different Binding RelativeSource Mode
    依赖属性和附加属性2(转载)
  • 原文地址:https://www.cnblogs.com/niuzaihenmang/p/5614650.html
Copyright © 2020-2023  润新知